-gustw
Last Updated: September 15, 2018
·
528
· nawazshahroz

Exception Handling in PHP 7.x versions

Error handling is one of the most important aspect in any development process. A good developer always do error/exception handling in the code. For achieving this goal they always pursue for the best practices in php. Because a single exception can break the whole application and can disrupt its processes. So your code must be well equipped with possible error reporting issues and the solutions to avoid them or remove them.

In older versions of PHP, you need to write your own exception classes, which contains manual logics in try catch blocks. But thanks to contributors and developers of PHP for eradicating this unwanted hassle in newer versions i.e PHP 7.x. As we can now dedicate classes and methods to handle exceptions and errors in the code.

In this article, I’ll introduce you these methods and will tell you how they can be used in the code. if you have production server on php mysql hosting than don't apply the upgrade changes directly to the files. Instead apply and test first on local or dev servers.

Before going in that part, I hope you have migrated your php application from older versions to the newer version. If not? then you can follow the php upgrade guide.

Quick Glance At Error Classes

The new dedicated error classes introduced in PHP 7.x are given below. They are arranged in the specific hierarchy that I’ll described them in the later part of the article.

  • Throwable
  • Error
    • ArithmeticError
      • DivisionByZeroError
    • AssertionError
    • ParseError
    • TypeError
      • ArgumentCountError
  • Exceptions

Since error reporting and exception handling is changed in PHP 7.x and instead of handling errors from traditional mechanisms, they can now be handled from Error Exception classes which extends Throwable.

Throwable

Throwable is the base interface extend by both Errors and Exceptions. This Class helps you to catch any kind of errors but noted that you can not extend Throwable interface directly in PHP classes. You must extend the exception class for this.

The simplest way to initialize throwable in exception is like:

try {
    // Code that may throw an Exception or Error.
} catch (Throwable $t) {
    // Handle exception
}

Let’s see the example below:

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

Another example is this Parse Error (available in PHP 7.x)

<?php
try {
$result = eval("2*'7'");
}
catch(Throwable $e){
        echo $e->getMessage();
}

Error

Error is a reserved keyword now and the error class can handle all kind of type errors and fatal errors. In simple words, you can say Error is a base class to handle all internal errors. Usually an instance of the base Error class is thrown from previously fatal errors. But some errors will throw a more specific subclass of Errors given below:

  • TypeError
  • ParseError
  • AssertionError
  • Arithmetic Errors

Arithmetic Errors

Arithmetic Errors extends the base class Error and occurs while performing mathematical operations in the code. intdiv() is the simplest example of it:

<?php

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

You will get the negative value for PHPINTMIN by -1 because I’ve transferred it by negative amount.

DivisionByZero error extends the Arithmetic Error class and occurs when a number is divided by zero.

Let’s see an example:

<?php
   class MathOperations {
      protected $n = 10;

      // Try to get the Division by Zero error object and display as Exception
      public function doOperation(): string {
         try {
            $value = $this->n % 0;
            return $value;
         } catch (DivisionByZeroError $e) {
            return $e->getMessage();
         }
      }
   }

   $mathOperationsObj = new MathOperations();
   print($mathOperationsObj->doOperation());
?>

The output of the code will be Modulo by zero in the browser.

AssertionError

This error occurs when the condition set by assert() method will not met to expected result. Thus, assertion exception thrown. Lets see the example:

ini_set('zend.assertions', 1);
ini_set('assert.exception', 1);

$test = 1;

assert($test === 0);

This will produce the following output:

Fatal error: Uncaught AssertionError: assert($test === 0)

Before the addition of the AssertionError class, you had to create your own functions to handle assertion exceptions when binding a custom function using assert_options(). This error will only be shown when an assertion made via assert() fails. To work with it, you first need to configure the assert directives in PHP.ini:

By default, assert.exception value is 0 in php.ini and you can change it to 1 to catch AssertErrors. Similarly, By default, Zend.assertions value is -1 which is for production mode, i.e., the assertion code will not be generated. When it is set to 1 it will be in development mode in which assertion code will be generated and executed. When it is set to 0, assertion code will be generated but won’t be executed during runtime.

ParseError

This Error is thrown when you are trying to add a code line using eval() or requiring a file using require() and the file contains any error. The fatal error will be thrown in the exception.

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

And, we are calling it in another PHP file:

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

The output of this code will be seen like this on browser: syntax error, unexpected end of file .

TypeError

TypeError can be thrown if these three issues are raised in your code:

The argument type being passed to a function that does not match its corresponding declared parameter type.
The value being returned from a function that does not match the declared function return type.
The third is where an invalid number of arguments are passed to a built-in PHP function (strict mode only).

Lets see an example of this:

function add(int $left, int $right)
{
    return $left + $right;
}

try {
    $value = add('left', 'right');
} catch (TypeError $e) {
    echo $e->getMessage(), "\n";
}

The output will be this on browser.

Argument 1 passed to add() must be of the type integer, string given

Final Word

Open source developers are workig hard to make PHP a robust language with the newer versions. At the time of writing this article PHP 7.3 RFC is out and you can expect so many changes with the ongoing updates. Till then use the above errors and exception methods to avoid possible errors in your projects.