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.
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.
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.
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.
a try{} block then PHP5 will jump into the “catch” section for exception handling.