PHP catch Keyword
Example
Catch an exception:
<?php
try {
throw new Exception("This is an exception");
}
catch(Exception $e) {
echo $e->getMessage();
}
?>
Try it Yourself »
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.
Read more about try..catch.finally (Exceptions) in our PHP Exceptions Tutorial.
More Examples
Example
Use catch for multiple types of exception:
<?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";
}
?>
Try it Yourself »
❮ PHP Keywords
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.