PHP Exception Handling

In this PHP tutorial, you will learn all about Exception Handling in PHP. We will discuss in detail the try, catch, throw and finally statements.

What is meant by Exception Handling in PHP?

An exception is an unexpected result of a program that can be handled by the programming. An exception, in essence, disturbs the usual flow of the program. However, it differs from an error in that an exception may be handled, but an error cannot be controlled by the script. An exception acts as a signal that an extraordinary occurrence or error has happened. Exceptions can occur for a variety of reasons, such as a failed database connection or query, a file that you are attempting to access that does not exist, and so on. PHP has a robust exception handling structure that enables you to handle errors appropriately. Exception handling, as opposed to PHP's standard error-handling method, is an object-oriented technique for managing problems that enables a more controlled and flexible type of error reporting. PHP version 5 was the first to provide an exception model.

PHP : Html Form

The following terms are used to handle the exceptions:

  •     try – 

    The try block includes code that might cause an exception or where an exception could occur. When an exception occurs within the try block while the script is executing, it is caught and resolved in the catch block. The try block is required to be followed by a catch or finally block. A try block can be followed by any number of catch blocks, with a minimum of at least one catch block.

  •     catch – 

    The catch block includes the code that is executed when an exception of a specific type of exception is thrown. It is only used in connection with a try block, never on its own. When an exception occurs, PHP looks for the corresponding catch block.

  •     throw – 

    It is a keyword that is used to generate an exception. It is also beneficial to record all of the exceptions that a function throws but does not handle. Likewise, the try blocks the thrown block also should contain at least one catch block.

  •     finally – 

    Finally, there is code in the finally block that is used for cleaning PHP script activities. Essentially, it performs the program's core code.

What are the advantages of using Exception Handling in PHP?

  •     Grouping of error types:

    In PHP both basic and object exceptions can be thrown. It can build a hierarchy of exception objects, arrange exceptions into classes, and categorize them based on their types.

  •    Keep error handling and normal code separate:

    To handle errors in the conventional error handling method, it usually uses an if-else block. These conditions and error-handling code become complicated and make it unreadable. The try Catch block makes the code much more understandable.

Examples

Example 1: To show the basic use of the exceptions

When an exception is thrown, instead of executing the PHP script following the code it will try to find the corresponding "catch" block. If an exception is not caught, then a fatal error will be issued with an "Uncaught Exception" message.

Let's try to divide a number by 0


<?php
try {
 $num1 = 10;
 $num2 = 0;
 if ($num2 == 0)
  throw new Exception("Can't divide by 0");
 else {
  echo $num1 / $num2;
 }
} catch (Exception $e) {
 echo 'Message: ' . $e->getMessage();
}
?>

Output:


Message: Can't divide by 0

In the above example, we are checking whether the program is trying to divide a number by 0 or not. In this program, we have written the code in the try block and check that if the divisor is 0 then it will throw an error otherwise it will print the result of the value after the division.

Example 2: To use multiple catch block


<?php
class ExceptionDivideByZero extends Exception
{
}
class ExceptionDivideByNegativeNum extends Exception
{
}
function checkNum($dividend, $divisor)
{
 try {
  if ($divisor == 0) {
   throw new ExceptionDivideByZero;
  } else if ($divisor < 0) {
   throw new ExceptionDivideByNegativeNum;
  } else {
   $result = $dividend / $divisor;                echo "Result of divisi \n";
  }
 } catch (ExceptionDivideByZero $dze) {
  echo "Trying to Divide by Zero Exception! \n";
 } catch (ExceptionDivideByNegativeNum $dnne) {
  echo "Trying to Divide by Negative Number Exception \n";
 } catch (Exception $ex) {
  echo "Unknown Exception";
 }
}
checkNum(13, 7);
checkNum(40, -5);
checkNum(17, 0);
?>

Output:


Result of divisi                     
Trying to Divide by Negative Number Exception 
Trying to Divide by Zero Exception!

In the above example, we are checking whether the program is trying to divide a number by 0 and a negative number or not. In this program, we have created custom exceptions accordingly. And we have written the checking script in the function which contains the try block. And we have a catch block for every exception.

How to Set a Top-Level Exception Handler in PHP?

If an exception is not caught, PHP creates a Fatal Error with the message "Uncaught Exception...". This error message may include sensitive information such as the file name and line number where the fault occurred. If you don't want to give such information to the user, you may write your own custom function and register it with the set_exception_handler() method to handle any uncaught exceptions.
Example  


<?php
function myException($exception)
{
 echo "Exception: " . $exception->getMessage();
}
set_exception_handler('myException');
throw new Exception('Uncaught Exception occurred');
?>

Output:


Message: Can't divide by 0 Exception: Uncaught Exception occurred