Exception Handling in PHP

Exceptions are important to control over error handling. Exception handlings are used to change the execution of a code if a specified error occurs.

Here are some keywords related to exception handling:

·         Try: A function which is using an exception must be in a ‘try’ block. If the exception is triggered, an exception is thrown, otherwise if exception does not trigged, the code will continue its execution.

·         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 information about exception.


// function is created with an exception

function check($num) {

  if($num>2) {

    throw new Exception("Value must be 2 or below");


  return true;



// exception is triggered  in a "try" block

try {

  check (3);

  //If the exception is thrown, this text will not be shown

  echo ' the number is 2 or below';



//catch exception

catch(Exception $e) {

  echo 'Message: ' .$e->getMessage();





Message: Value must be 1 or below


Example explained

·         The check() function is created. It checks whether a number is greater than 2.If it is, than an exception is thrown.

·         The check() function is called in a “try” block.

·         The exception within check() function is thrown.

·         After exception is thrown the catch block retrieves the exception and creates an object ($e) containing the information about exception.

·         The error message is displayed by calling $e->getMessage() from the exception object.

Creating a custom Exception class in PHP

You can create your own custom exception handler. To create a custom exception handler you must create a special class function. This function is called when an exception occurs in PHP. The class must be an extension of the exception class. Use following function to set a user-defined exception handler function:

string set_exception_handler ( callback $exception_handler )


When uncaught exception occurs than exception_handler (the name of the function) is called.


   function exception_handler($error) {

      echo "An uncaught exception: " , $error->getMessage(), "\n";



   throw new Exception('Uncaught Exception');


   echo “This is not Executed\n";


Leave Comment