How To Use Exceptions Handling in PHP Example ?




How To Use Exceptions Handling in PHP Example ?

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.


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".


This is how you trigger an exception. Each "throw" must have at least one "catch".


A "catch" block retrieves an exception and creates an object containing the exception information.


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


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';



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 )



function exception_handler($exception) {

echo "Uncaught exception: " , $exception->getMessage(), "\n";



throw new Exception('Uncaught Exception');

echo "Not Executed\n";



Uncaught exception: Uncaught Exception

Now you can check your own.

I hope it can help you...

#PHP 8