03-Apr-2023
.
Admin
Hi guys,
Today i will explained How To Use Exceptions Handling in PHP. This example is so easy to use in php. The exception model similar to that of other programming languages. Exceptions are important and provides a better control over error handling.
Lets explain there new keyword related to exceptions.try,throw,catch block.
So let's start to the example.
try
Function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown".
Throw
This is how you trigger an exception. Each "throw" must have at least one "catch".
Catch
A "catch" block retrieves an exception and creates an object containing the exception information.
Example
In the above example $e->getMessage function is used to get error message. There are following functions which can be used from Exception class.
getMessage() - message of exception
getCode() - code of exception
getFile() - source filename
getLine() - source line
getTrace() - n array of the backtrace()
getTraceAsString() - formated string of trace
<?php
try {
$error = 'Always throw this error';
throw new Exception($error);
echo 'Never executed';
}catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
echo 'Hello World';
?>
Output
Caught exception: Always throw this error Hello World
Creating Custom Exception Handler
You can define your own custom exception handler. Use following function to set a user-defined exception handler function.
string set_exception_handler ( callback $exception_handler )
Example
<?php
function exception_handler($exception) {
echo "Uncaught exception: " , $exception->getMessage(), "\n";
}
set_exception_handler('exception_handler');
throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>
Output
Uncaught exception: Uncaught Exception
Now you can check your own.
I hope it can help you...
#PHP 8
#PHP