Creating Exceptions in PHP Using Try and Catch

In addition to handling various classes of exceptions with multiple catch blocks within a try block, custom exception classes can also be created to manage uncatchable exceptions, in addition to the PHP exception class and its subclasses.

The try-catch blocks in PHP are equipped with exception handling features and are responsible for handling exceptions. These blocks play a crucial role in exception handling. Additionally, the try-catch block is used alongside the keyword “throw” which is utilized for throwing exceptions.

A catch block is mandatory for every try block, but
multiple catch blocks
can also be used within a try block to handle different types of exceptions.

Syntax

To manage runtime errors, the subsequent syntax is utilized in exception handling.


Delve deeper into the concept of try-throw-catch with me.

try

The try block encloses the code that is vulnerable to exception. If an exception is raised during runtime in the try block, it is handled by the catch block. Hence, it is mandatory for each try block to have at least one catch block. The catch block comprises the code block where an exception can arise.

Some key observations should be made regarding the attempt.

  • It is necessary to have a catch or finally block after the try block.
  • It is mandatory for a try block to contain a catch block, with a minimum of one.
  • It’s possible to have several catch blocks associated with a single try block.
catch

When an exception is raised in the try block, the catch block comes into action and contains the code to handle the exception. The throw keyword in the try block triggers the exception. The catch block is executed only when a particular exception is thrown. PHP searches for the corresponding catch block and assigns the exception object to a variable.

Here are some important observations to make regarding the catch:

  • A try block can have multiple catch blocks.
  • One or more catch statements catch and resolve the thrown exception.
  • A try block must always be used in conjunction with a catch block as it cannot be used independently.
  • It follows the try block.
throw

The “throw” keyword is utilized to raise an exception, and it should be noted that there must be at least one corresponding “catch” block to handle the exception.

The function’s list of thrown exceptions is comprised of those that cannot be dealt with by the function internally.

finally

The main code for program execution is enclosed in a block referred to as “essential code”. Additionally, in PHP, the finally block is utilized for performing clean-up tasks, similar to how the catch block is utilized for handling exceptions. The only distinguishing factor is that the finally block is always executed, regardless of whether an exception is handled or not.

The finally block, which executes after the try and catch block regardless of whether an exception has been thrown or not, can be placed either after or in place of the catch block. It is commonly used for tasks such as closing database connections and streams.

Example 1

To illustrate the typical sequence of throw and try-catch, as well as the finally block, we can use an example.

=1) {
     //throw an exception
     throw new Exception("Value must be less than 1");
   }
   return true;
}

//trigger an exception in a "try" block
try {
   checkNumber(5);
   //If the exception throws, below text will not be display
   echo 'If you see this text, the passed value is less than 1';
}

//catch exception
catch (Exception $e) {
   echo 'Exception Message: ' .$e->getMessage();
}
finally {
   echo ' It is finally block, which always executes.';
}
?>


Output:

Exception Message: Value must be less than 1
It is finally block, which always executes.
Example 2
  If you see this text, the passed value is an EVEN Number ';
     }
     //catch exception
     catch (Exception $e) {
         echo '  Exception Message: ' .$e->getMessage() .'';
     }
     finally {
        echo ' It is finally block, which always executes.';
     }
}
      echo 'Output for ODD Number';
      testEven(19);
      
      echo ' ';
      echo 'Output for EVEN Number';
     testEven(12);

?>


Output:

The output below displays an exception message when an odd number is passed, and another message is shown when an even number is passed.

Output for ODD Number 
Exception Message: Passed number is an ODD Number
It is finally block, which always executes.

Output for EVEN Number
If you see this text, the passed value is an EVEN Number
It is finally block, which always executes.
Example 2: Custom Exception and Multiple catch statement

The forthcoming example illustrates the creation of a custom exception class that extends the Exception class, along with the utilization of a single try block accompanied by multiple catch blocks.

  If you see this text, the passed value is an EVEN Number ';
     }
     
     //catch exception
     catch (OddNumberException $ex) {
         echo '  Exception Message: ODD Number' .'';
     }
     //catch exception
     catch (Exception $e) {
         echo '  Exception Message: ' .$e->getMessage() .'';
     }

}
   echo 'Output for EVEN Number';
   testEven(28);
   echo ' ';
   echo 'Output for ODD Number';
   testEven(17);
?>


Output:

Output for EVEN Number
If you see this text, the passed value is an EVEN Number 

Output for ODD Number 
Exception Message: ODD Number

Crucial highlights:

  • Custom exception classes can be used to handle uncatchable exceptions, in addition to PHP’s exception class and its subclasses.
  • PHP 5.5 and later versions utilize the final block for managing exceptions. This block is executed without fail, regardless of whether an exception is thrown or not.

Frequently Asked Questions

Posted in Php