PHP | set_exception_handler() Function

PHP set_exception_handler() Function


Hello folks! welcome back to a new section of our tutorial on PHP. In this tutorial guide, we are going to be studying about the PHP set_exception_handler() Function.

The PHP set_exception_handler() function is used to set the default exception handler if no exception is caught within a try/catch block. Execution will stop after exception handler is called.

Syntax

Following below is the syntax to use this function -

string set_exception_handler ( callback $exception_handler );


Parameter Details

Sr.NoParameter & Description
1

exception_handler

Name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler(). This handler function needs to accept one parameter, which will be the exception object that was thrown.


Return Value

This built-in PHP function returns the name of the previously defined exception handler, or NULL on an error. If no previous handler was defined, then NULL is also returned.

Example

Try out the below example -

<?php
   function exception_handler($exception) {
      echo "Uncaught exception is : " , $exception->getMessage(), "\n";
   }
   
   set_exception_handler('exception_handler');
   set_exception_handler();
   
   throw new Exception('Not Found Exception');
   echo "not included Executed\n";
?> 

Output

When the above code is executed, it will produce the following result -

Uncaught exception is: Not Found Exception


Alright guys! This is where we are rounding up for this tutorial post. In our next tutorial guide, we are going to be discussing about the PHP trigger_error() Function

Do feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.