Example
Catch an exception:
html
<?php
try {
throw new Exception("This is an exception");
}
catch(Exception $e) {
echo $e->getMessage();
}
?>
Definition and Usage
The catch keyword is used to handle exceptions that are thrown by the code in a preceding try block.
Related Pages
The throw keyword.
The try keyword.
The finally keyword.
More Examples
Example
Use catch for multiple types of exception:
html
<?php
try {
$rand = rand(0, 2);
switch($rand) {
case 0: throw new Exception();
case 1: throw new
OutOfBoundsException();
case 2: throw new
LogicException();
}
} catch(OutOfBoundsException $e) {
echo "Caught an out of bounds exception";
} catch(LogicException $e) {
echo "Caught a logic exception";
} catch(Exception $e) {
echo
"Caught an ordinary exception";
}
?>