Use a try statement to catch exception in PHP
Description
The following code shows how to use a try statement to catch exception.
Example
<?php// ww w . j a va 2s .c o m
//derive math exception from base class
class mathException extends Exception
{
public $type;
public function __construct($type)
{
//get filename and line number
parent::Exception();
$this->type = $type;
}
}
//try a division
$numerator = 1;
$denominator = 0;
try
{
//throw exception on divide by zero
if($denominator == 0)
{
throw new mathException("Division by zero");
}
print($numerator/$denominator);
}
catch(mathException $e)
{
//we caught a math exception
print("Caught Math Exception ($e->type) in " .
"$e->file on line $e->line<br>\n");
}
catch(Exception $e)
{
//we caught some other type of exception
print("Caught Exception in " .
$e->file() . " on line " .
$e->line() . "<br>\n");
}
?>