Search⌘ K

Non-exception Error Handling Techniques

Explore various techniques to handle errors in PHP without exceptions, including using callbacks, default values, PHP error messages, and sum types. Understand how these approaches reduce overhead and improve code clarity in functional programming.

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 ...