Notice: A non well formed numeric value encountered in C:\ClientSites\bestaspnethostingreview.com\httpdocs\wp-content\plugins\crayon-syntax-highlighter\crayon_formatter.class.php on line 118
Notice: A non well formed numeric value encountered in C:\ClientSites\bestaspnethostingreview.com\httpdocs\wp-content\plugins\crayon-syntax-highlighter\crayon_formatter.class.php on line 119
Notice: A non well formed numeric value encountered in C:\ClientSites\bestaspnethostingreview.com\httpdocs\wp-content\plugins\crayon-syntax-highlighter\crayon_formatter.class.php on line 118
Notice: A non well formed numeric value encountered in C:\ClientSites\bestaspnethostingreview.com\httpdocs\wp-content\plugins\crayon-syntax-highlighter\crayon_formatter.class.php on line 119
BestASPNETHostingReview.com | Best and cheap PHP 7 Hosting. In this post I would like to show to how to handling multiple exceptions in PHP 7. Exception handling is one of the ways in which modern languages handle errors. PHP usually handles exception in a separate catch block for each different type of exception. Below is a example exception code that uses three custom exceptions ‘MyFooException’, ‘MyBarException’ and ‘MyBazException’ that is later handled in a ‘try’ block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <?php class MyFooException extends Exception { public function __construct($message = null, $code = 0) { echo $message; } } class MyBarException extends Exception { public function __construct($message = null, $code = 0) { echo $message; } } class MyBazException extends Exception { public function __construct($message = null, $code = 0) { echo $message; } } try { $error = "Baz Exception thrown."; throw new MyBazException($error); } catch(MyFooException $e) { echo "Caught a 'Foo' Exception"; // Do something here } catch(MyBarException $e) { echo "Caught a 'Bar' Exception"; // Do something here } catch(MyBazException $e) { echo "Caught a 'Baz' Exception"; // Do something here } |
Note that if each catch block has the same code to handle the exception than the result is code duplication. Now in PHP 7.1 you can handle multiple types of exceptions in a single catch block by using a pipe ‘|’ character. The above code to handle the exception will now be changed as below; assuming that the code in the catch block will be the same to handle all three exception types.
1 2 3 4 5 6 7 | try { $error = "Foo / Bar / Baz Exception"; throw new MyBazException($error); } catch(MyFooException | MyBarException | MyBazException $e) { // Do something here } |
This now prevents code duplication and any error from creeping in if one the catch block is handled differently than the other.