First of all, we need to understand what is the exception and how we can encounter it. The exceptions are uncaught errors. The errors that can terminate the complete work must be caught before it messes up the complete project.
PHP has two built-in Exceptions, that can catch the errors generated in the Try block only if we have implemented the Exception Handling correctly.
- Exception
- Error Exception
In PHP 7 Throwable Exception has been introduced. We can throw an error or exception manually instead of displaying the fatal to the end-user so that it can be caught by the catch block.
Here is the complete hierarchy of the Exception classes introduced in PHP 7.
Throwable
- Error
- ArithmeticError
- DivisionByZeroError
- AssertionError
- ParseError
- TypeError
- ArithmeticError
- Exception
- ClosedGeneratorException
- DOMException
- ErrorException
- IntlException
- LogicException
- BadFunctionCallException
- BadMethodCallException
- DomainException
- InvalidArgumentException
- LengthException
- OutOfRangeException
- BadFunctionCallException
- PharException
- ReflectionException
- RuntimeException
- mysqli_sql_exception
- OutOfBoundsException
- OverflowException
- PDOException
- RangeException
- UnderflowException
- UnexpectedValueException
In PHP 7 there is the parent Class Throwable and all the exceptions come under this class.
So here we see why we need the error and exception handling to prevent our code from throwing the fatal in front of the users.
This is the simple code and the output where we have not used any error handling.
<?php error_reporting(E_ALL); ini_set('display_errors', TRUE); ini_set('display_startup_errors', TRUE); class customException extends Exception { function index($var1, $var2) { echo "\n value1 = " . $var1; echo "\n value2 = " . $var2; $result = $var2%$var1; } } $obj = new customException(); $obj->index(0,5); ?>
See what we got from the code the fatal error that can stop our complete work and we don’t want that.
Here is the example with the output where we have used the proper error handling:
<?php error_reporting(E_ALL); ini_set('display_errors', TRUE); ini_set('display_startup_errors', TRUE); class customException extends Exception { function index($var1, $var2) { echo "\n value1 = " . $var1; echo "\n value2 = " . $var2; try { $result = $var2%$var1; } catch (DivisionByZeroError $e) { echo "\n Exception Caught in DivisionByZeroError ", $e->getMessage(); } catch(Error $e) { // In case the above catch failed to catch the errors echo "\n Exception Caught in Error ", $e->getMessage(); } } } $obj = new customException(); // Exception will be rised $obj->index(0,5); ?>
This is the basic explanation of what is an exception and why we need the exception and error handling in our code.
I hope this blog helps you in understanding the Exception Handling. Thanks.
Be the first to comment.