PHP Exceptions
An exception is an error object that a program can throw and catch. A try block runs code that might throw, and a catch block handles the exception.
A thrown exception is caught
A function throws an exception for an age under 18. Catch prints its message.
<?php
function checkAge($age) {
if ($age < 18) {
throw new Exception("Too young");
}
echo "Welcome\n";
}
try {
checkAge(15);
} catch (Exception $e) {
echo $e->getMessage(), "\n";
}
echo "Program continues\n";A try block with no error
Nothing throws inside this try block. Its line prints and catch stays silent.
<?php
try {
echo "All good\n";
} catch (Exception $e) {
echo $e->getMessage(), "\n";
}Division by zero is caught
Dividing by zero throws a different kind of error. Catch prints its class name and message.
<?php
try {
echo 10 / 0, "\n";
} catch (DivisionByZeroError $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
}finally runs on both paths
The same function runs with a young age and an older age. The finally line prints after each call.
<?php
function attempt($age) {
try {
if ($age < 18) {
throw new Exception("Too young");
}
echo "Welcome\n";
} catch (Exception $e) {
echo $e->getMessage(), "\n";
} finally {
echo "Check done\n";
}
}
attempt(15);
attempt(21);Example
<?php
function checkAge($age) {
if ($age < 18) {
throw new Exception("Too young");
}
return "Welcome";
}
try {
echo checkAge(15), "\n";
} catch (Exception $e) {
echo $e->getMessage(), "\n";
}
try {
echo checkAge(21), "\n";
} catch (Exception $e) {
echo $e->getMessage(), "\n";
}Key points
- Use try to run code that might throw an exception.
- Use catch to handle an exception thrown in the try block.
- Use throw new Exception with a message to raise an exception.
- Call getMessage() to read the message stored in an exception.
- A finally block runs whether the try block threw or not.
- After catch handles an exception, the program continues.
In this example, checkAge returns a welcome line for an age of 18 or more. It throws an exception for a younger age. The first call throws and catch prints Too young. The second call returns Welcome and that line prints.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz PHP Compiler
Exercise
A checkAge(15) call throws an Exception with the message "Too young". What does catch print when it uses getMessage()?