PHPBuilder - Introduction to PHP5 Page 7



RSS Twitter
Articles Tricks And Hacks

Introduction to PHP5 - Page 7

by: Luis Argerich
|
April 11, 2003

Exceptions

Exceptions are an accepted way to handle errors and unexpected conditions in languages such as Java and C++, PHP5 incorporates exceptions implementing the "try" and "catch" hooks.
Example 12: Exceptions

<?php
class foo {

  function 
divide($x,$y) {
    if(
$y==0) throw new Exception("cannot divide by zero");
    return 
$x/$y;
  }
}

$x = new foo();

try {
  
$x->divide(3,0);   
} catch (
Exception $e) {
    echo 
$e->getMessage();
    echo 
"\n<br />\n";
    
// Some catastrophic measure here
}
?>
As you can see you use "try" to denote a block of code where exceptions will be handled by the "catch" clause at the end of the block. In "catch" you should implement whatever you need as your error handling policy. This leads to cleaner code with only one point for error handling.

Defining your own exceptions

You can define custom exceptions to handle unexpected problems in your programs. You only need to extend the Exception class implementing a constructor and the getMessage method.
Example 13: Custom exceptions

<?php
class WeirdProblem extends Exception {

   private 
$data;

   function 
WeirdProblem($data) {
        
parent::exception();
        
$this->data $data;
    }

    function 
getMessage() {
        return 
$this->data " caused a weird exception!";
    }
}
?>
Then use throw new WeirdProblem($foo) to throw your exception, if the exception is produced inside a try{} block then PHP5 will jump into the "catch" section for exception handling.

« Previous Page
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Luis Argerich

Comment:



Comment:

(Maximum characters: 1200). You have characters left.