Exception handling in PHP

PHP5 supports exception handling with try and catch blocks. This can be used to notify the user of any exceptions. This example uses a modified version of the Person class of the Inheritance in PHP example to throw an exception if an invalid age has been supplied. The catch block is used to catch the exception and print it to the user.

<?php

try {

    // Create the first Person instance
    $firstPerson = new Person('Santa',191);
    $firstPerson->Walk();

    // Attempt to create the second Person instance with an invalid age
    $secondPerson = new Person('Foo','bar');
    $secondPerson->Walk();

} catch(Exception $exception){
    print "Exception: " . $exception->getMessage()."\n";
}

class Person {

  protected $name;
  protected $age;

  function __construct($name,$age){
    $this->name = $name;

    if(is_numeric($age) && $age > 0){
        $this->age = $age;
    } else {
        throw new Exception("Invalid age supplied");
    }
  }

  public function Walk(){
    print $this->name.": Walking!\r\n";
  }
}

?>

Output:

Santa: Walking!
Exception: Invalid age supplied

On a side note, a custom exception handler can be supplied with the set_exception_handler function.

This entry was posted in PHP and tagged , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?