The term exception describes an unexpected program, and it changes the flow of code if any conditional error occurs. Generally, it’s used to control unexpected errors in the program.
Here is an example of exception handling in PHP, where we require an input that must be an even number.
<?phpfunction checkeven($number) {if($number%2!=0) {throw new Exception("<< Value must be an even number >>");}return true;}checkeven(3);?>
checkeven()
function with the argument, $number
.<< Value must be a even number >>
if the number is odd.There are few problems with exception handling. For instance, it breaks the referential transparency (that is, the function will return the same value if it’s called with the same argument) and increases the complexity of the code. Moreover, exception object creation and stack trace calculation put a lot of strain on the runtime.
To overcome this issue, there are three important non-exception error handling techniques in PHP.
Callbacks refer to a function that is passed in another function as an argument. Instead of exception handling, we can use this function to avoid runtime strains.
In the code example given below, the get_head()
function is supposed to return the first index of the integer-indexed array. What if the user passes a string indexed array?
<?phpfunction get_head(array $numbers){return $numbers[0];}// the string indexed array.$myarray = array("foo" => "bar","bar" => "foo",);echo get_head($myarray)?>
There must be a callback function here to handle the exception. Let’s look at the solution of the above problem using the callback function.
<?phpfunction get_head(array $numbers, callable $callback){return isset($numbers[0]) ? $numbers[0] : $callback($numbers);}$myarray = array("foo" => "bar","bar" => "foo",);echo get_head($myarray,'reset');?>
In this case, we can display the error message using the trigger_error()
function whenever an exception appears.
Let’s look at the example in which the increment()
function is given with one parameter $num
. This function is supposed to add 1
in the variable $num
. What if the user passes a string into the function? For this problem, we’ll use the trigger_error()
function in our program.
<?phpfunction increment($num):int{return is_int($num) ? $num+1: trigger_error("non numeric value encountered",E_USER_WARNING);}echo increment("Hello");?>
In PHP, we can define the default values for error handling. This will work like the callback functions.
Let’s look at an example of default values. We use the same code that we used in the callback example. In addition to the previous one, we’ve added a default value. So, if the array is integer-indexed, then the programs will return the default value.
<?phpfunction get_head(array $numbers, $default="index value must be a string"){return isset($numbers[0]) ? $numbers[0] : $default;}$myarray = array("foo"=>"Hello","boo"=>"world",);echo get_head($myarray);?>
Free Resources