Php Exception Handling

xception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.

  • The current code state is saved
  • The code execution will switch to a predefined (custom) exception handler function
  • Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code
  • Basic Use of Exceptions

    When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block.

    Example :-

    Try, throw and catch

    To avoid the error from the example above, we need to create the proper code to handle an exception.

    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

    Example :-

    Creating a Custom Exception Class

    To create a custom exception handler you must create a special class with functions that can be called when an exception occurs in PHP. The class must be an extension of the exception class.

    Example :-

    Multiple Exceptions

    It is possible for a script to use multiple exceptions to check for multiple conditions.

    It is possible to use several if..else blocks, a switch, or nest multiple exceptions. These exceptions can use different exception classes and return different error messages:

    Example :-