...

/

Non-exception Error Handling Techniques

Non-exception Error Handling Techniques

Learn about non-exception-based error handling techniques like callbacks, PHP error messages, default values, and sum types.

We'll cover the following...

The following techniques are among the error handling techniques that are not based on exceptions:

  • Callbacks
  • PHP error messages
  • Default values
  • Sum types

Callbacks

A callback is a function that serves as an argument of a higher-order function. Callbacks mitigate failure when they’re used in place of exceptions. Consider the following snippet:

PHP
<?php
function head(array $numbers)
{
return $numbers[0];
}
echo head([1,2,3,4,5]);
?>

The head function shown above returns the first index of an integer-indexed array. The sample size for the function above is every collection with integer indexes. Suppose one intends to supply a string-indexed list to the head function. The result will likely be a notice similar to the one shown below:


PHP Notice: Undefined offset: 0 in php shell code on line 1

Notice: Undefined offset: 0 in php shell code on line 1

Typically, an exception is used to address the possibility of parsing a non-integer-indexed list, but the costly nature of exception-object creation and stack-trace generation warrants preemption. A simple callback ...