Monday, October 31, 2016

A Crash Course of Changes to Exception Handling in PHP 7

Exception handling saves your code in the most unusual circumstances. PHP 7 has introduced two new classes that assist a developer in handling errors with ease, and that's what we'll look at in this post. Before the introduction of these classes in PHP 7, exception error classes were written to handle the different types of errors.

Illustration of female leg stepping on rake with the word Oops in big letters, indicating pending accident

Throwable Class

Throwable is the interface from which, Exception and Error classes branch out. This particular class helps you catch any throwable errors, irrespective of whether they are an exception or an error. For example:

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

Or 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().

User defined classes cannot implement Throwable directly, and must instead extend Exception which implements Throwable.

Error Class

The Error class in PHP 7 is a new type of class that handles the different errors - they are either fatal errors or type errors, and this class is only for internal PHP errors. Error is divided into four subclasses:

Continue reading %A Crash Course of Changes to Exception Handling in PHP 7%


by Ahmed Khan via SitePoint

No comments:

Post a Comment