4.7. Handling Errors with Exceptions

PHP provides an error-handling class called Exception. You can use this class to handle undesirable things that happen in your script. When the undesirable thing that you define happens, code in your method creates an exception object. In object-oriented talk, this is called throwing an exception. Then, when you use the class, you check whether an exception is thrown and perform specified actions.

You can throw an exception in a method with the following statement:

throw new Exception("message");

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.

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 over 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(); ...

Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.