PHP - Exception Handling

PHP 5 has an 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 − A 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.
  • When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception

  • An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block.
  • Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions.
  • Exceptions can be thrown (or re-thrown) within a catch block
  • Example -

    Creating Custom Exception Handler

    You can define your own custom exception handler. Use following function to set a user-defined exception handler function.

    Here exception_handler is the name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler().

    Example -