PHP Exception Handling

PHP provides an error-handling class called Exception. PHP 5 introduced new object oriented way of dealing with errors. Exceptions are used to change the normal flow of a script if a specified error occurs.

images/articles/php/php-exception-handling.jpg

An exception is an event that occurs during the runtime of a program, and that disrupts its normal flow. Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs.

When an error occurs, it is transformed into an object (the exception object) that contains relevant information about the error and the location where it was triggered. We can throw and catch exceptions in a PHP script.

When the exception is thrown, it is handed to the runtime system, which will try to find a place in the script where the exception can be handled. This place that is looked for is called the exception handler, and it will be searched for in the list of functions that are called in the current runtime, until the exception was thrown. This list of functions is known as the call stack

When an exception is thrown, the code following it is not executed. PHP tries to find the matching "catch" block. If an exception is not caught, a fatal error is issued with an "Uncaught Exception" message. To avoid the error, you need to create the proper code to handle an exception.

Proper exception code includes:

Try:  The try block is used to run any code that is expected to fail in an exceptional case (throwing an exception error). If the exception does not trigger, the code continues as normal. 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. The catch block is used to handle exceptions.

// Create function with an exception
function checkNum($number)
{
if ($number > 1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}

// Trigger exception in a "try" block
try
{
checkNum(2);
// If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}

// Catch exception
catch(Exception $e)
{
echo 'Message: ' . $e->getMessage();
}

The code above throws an exception and catches it. The checkNum() function checks if a number is greater than 1. If it is, an exception is thrown. The checkNum() function is called in a "try" block. The "catch" block retrieves the exception and creates an object ($e) containing the exception information. The error message from the exception is echoed by calling $e->getMessage() from the exception object.

Following functions can be used from Exception class.

  • getMessage(): message of exception
  • getCode(): code of exception
  • getFile(): source filename
  • getLine(): source line
  • getTrace(): n array of the backtrace()
  • getTraceAsString(): formated string of trace

Syntax for Throwing Exception

throw new Exception("This is an exception error");

This statement creates an Exception object and stores a message in the object. The Exception object has a getMessage method that you can use to retrieve the message you stored.

The keyword used to throw the exception is throw. The new Exception() creates an exception object and passes "This is an exception error" string as the message parameter.

Syntax for Try and Catch

The "try" code block is the code to be executed that could potentially raise an exception. The "catch (Exception $e)" code block catches the thrown exception and assigns the exception object to the variable $e.

try 
{
// Code goes here that could potentially throw an exception
}
catch (Exception $e)
{
// Exception handling code goes here
}

Example

In your class definition, you include code in your methods to create an Exception when certain conditions occur. For example, the addGas method in the following Car class checks whether the amount of gas exceeds the amount that the car gas tank can hold, as follows:

class Car
{
private $gas = 0;
function addGas($amount)
{
$this->gas = $this->gas + $amount;
echo “<p>$amount gallons of gas were added</p>”;
if ($this->gas > 50)
{
throw new Exception(“Gas is overflowing”);
}
 }
}

If the amount of gas in the gas tank is more than 50 gallons, the method throws an exception. The gas tank doesn’t hold that much gas.

When you use the class, you test for an exception, as follows:

$my_car = new Car();
try
{
 $my_car->addGas(10);
 $my_car->addGas(45);
 }
catch(Exception $e)
{
 echo $e->getMessage();
 exit();
}

In the try block, you include any statements that you think might trigger an exception. In this script, adding too much gas can trigger an exception, so you add any addGas method calls inside a try block.

In the catch block, you catch the Exception object and call it $e. Then you execute the statements in the catch block. One of the statements is a call to a method called getMessage in the Exception class. The getMessage function returns the message that you stored, and your statement echoes the returned message. The script stops on the exit statement.

If no exception is thrown, the catch block has nothing to catch, and it is ignored. The script proceeds to the statements after the catch block. In this case, if the amount of gas doesn’t exceed 50 gallons, the catch block is ignored, and the script proceeds to the statements after the catch block.

Difference Between Errors and Exception

Exceptions are thrown and intended to be caught while errors are generally irrecoverable. Exceptions are handled in an object oriented way. When an exception is thrown; an exception object is created that contains the exception details.