Skip to main content

To help your code save from the unusual circumstances, as a web developer you can use an exception handling as one of the essential parts of your code. With PHP 7, you can manage your exception handling easier. In fact, it offers two new classes which aim for helping developers handling errors with ease. Interesting right? You can find the exception error classes with different type of errors which you can discover in the discussion below.

Throwable Class:
This class appears as one of the new classes introduced in PHP 7. In this class, you will see the exception and error classes branch out. If you happen to have many throwable errors with your previous program, you can catch any throwable errors, irrespective of whether they are an exception or an error.

<?php
try {
   throw new Exception(“This is an exception”);
}
catch (Throwable $e) {
    echo $e->getMessage();
}

Or any of the newly defined ParseError:

<?php
try {
    $result = eval(“2*’7′”);
}
catch (Throwable $e) {
    echo $e->getMessage();
}

After executing this code, you will get a ParseError because “;” is missing inside eval().

Error Class
In PHP 7, you will find an error class which manages different types of error exceptions – either they are fatal errors or type errors. Generally, error is categorized into four subclasses:

  1. ArithmeticError
  2. TypeError
  3. ParseError
  4. AssertionError

Bear in mind that you should have changed your custom error class having name error before upgrading to PHP 7. This aimed to prevent you from any Fatal Error.

In the following discussion we will give more detail information about the above four classes.

ArithmeticError
This error often occurs when you are performing mathematical operations. For instance, when you are using intdiv() in your function for some division, and after some calculation, a number is divided by 0 or -1, then an ArithmeticError will be thrown. Here is an example:

<?php
try {
    var_dump(intdiv(PHP_INT_MIN, -1));
}
catch (ArithmeticError $e) {
    echo $e->getMessage();
}

You will get “Division of PHP_INT_MIN by -1” because we have shifted it a bit by a negative amount. Another class, DivisionByZeroError, also extends from ArithmeticError. This error is thrown on two different conditions:

Note: You will get -1 only in combination with PHP_INT_MIN.

First, if you do a modulus of a number by 0, DivisionByZeroError occurs, showing “Modulo by zero” error message:

<?php
try {
    $result = 5 % 0;
    echo $result;
}
catch (DivisionByZeroError $e) {
    echo $e->getMessage();
}

However, if you use the same method as above and change the % by /, you will get warning instead of exception and the result can be any one from these: +INF, -INF, or NAN . However, you will have the DivisionByZeroError exception if you execute the following code:

<?php
try {
    $result = is_finite(1.0 / 0);
    if (in_array($result, [INF, NAN,-INF])) {
        throw new DivisionByZeroError(‘Division by zero error’)
    }
}
catch (DivisionByZeroError $e) {
    echo $e->getMessage();
}

The other method that will get you the DivisionByZeroError is by using intdiv().
Note: A bug report for this issue has been reported on PHP.net.

TypeError
This error is mostly used with the Scalar Type declarations in PHP 7. The error will be shown when you have created a function or variable of specific data type and you are trying to save a value of different data type. For example:

<?php
declare (strict_types = 1);
function add(int $a, int $b)
{
    return $a + $b;
}
try {
    echo add(“3”, “4”);
}
catch (TypeError $e) {
    echo $e->getMessage();
}

When you run the above code, TypeError exception will appear and get “must be of the type integer, string was given error, but if you run the above code without declare(strict_types=1); you won’t get any exception and the result will be 7 unless you change the number by a string like “name”.

ParseError
This error can be found usually when you are using eval() function to insert a new line of code or using an external PHP file which contains a syntax error. Before the ParseError, your code is broken and a fatal error is shown when you have a syntax error in your external PHP file or in eval() function. For instance, let’s assume we have a PHP file having the following code:

<?php
$a = 4
$result = $a * 5;

And, we are calling it another PHP file:

<?php
try {
require “index3.php”;
}
catch (ParseError $e) {
    echo $e->getMessage();
}

Instead of showing a fatal error, the following code will show, “syntax error, unexpected end of file” after it is executed. This class helps you in many conditions. For instance, your code will be broken if you have sent an irrelevant data. With this class, now it is possible to manage the syntax and fatal errors easier.

AssertionError
We have to create our functions to handle assertion exceptions to handle fatal errors when you have binded your custom function using assert_options() before the introduction of the AssertionError class. However, this error will only be shown when an assertion made via assert(), fails. To use this class, you need to configure the assert directives in PHP.ini file. There are two options that you can choose depending on your need.

  1. exception: By default, its value is 0 and it only generates warning for the object rather than showing the error. However, when the value is changed to 1, then it will throw you an exception or an Assertion Error, which can be caught by throwable or AssertionError, itself.
  2. assetions: By default, it’s value is -1 which is for production mode, i.e., the assertion code will be generated and executed. When it is set to 0, assertion code will be generated but won’t be executed in runtime.

For example, let’s make an assert which will fail.

<?php
try {
               assert(2 < 1, “Two is less than one”);
}
catch (AssertionError $ex) {
echo $ex->getMessage();
}

If you execute the code above, you will get only a warning that “assert(): Two is less than one failed” and your exception will not be caught because assert.exception is 0 and in order to make AssertionError catch the assert exception, we need to change assert.exception to 1. So when you run the following code:

<?php
ini_set(‘assert.exception’, 1);
try {
    assert(2 < 1, “Two is not less than one”);
}
catch (AssertionError $ex) {
    echo $ex->getMessage();
}

Instead of the warning, you will see that an exception is caught and only an exception message will be shown, i.e. “Two is less than one.”

Changes in Backward Compatibles
Many of the fatal and recoverable fatal errors have been inherited from the Error class since the introduction of new classes. It is not guaranteed that your custom handler, which you have set by using set_exception_handler(), will catch those errors. So, you don’t have to set your custom handler as it will not catch the errors by just using “Throwable”, if you want to throw some custom exceptions during your program.