PHP
The try/catch block
Learn to catch exceptions and handle error cases with try/catch.
What does try/catch do?
Some operations can throw errors: division by zero, opening a missing file, parsing an invalid date. try/catch catches these errors and prevents the program from crashing.
The try block runs risky code. If an exception is thrown inside, PHP stops normal flow and jumps to a matching catch block.
The catch parentheses declare which exception type to handle; the $e variable holds the exception object.
finally and multiple catch
After a try block you can write multiple catch clauses; each handles a different exception type. PHP picks the first match.
A finally block runs whether an exception was thrown or not; use it to close files or clean up resources.
catch (\Exception $e) catches every Exception subclass; if you name a specific type, only that one is caught.
Exercise Catch the error with try/catch
The call safeDivide(10, 0) throws a DivisionByZeroError. Call it inside try/catch, catch the error and print its message with an 'Error: ' prefix.
Show example solution
" . $e->getMessage() . "\n".
Example solution:
<?php
// Catch the division-by-zero error with try/catch
function safeDivide(int $a, int $b): int {
return intdiv($a, $b);
}
try {
echo safeDivide(10, 0) . "\n";
} catch (DivisionByZeroError $e) {
echo "Error: " . $e->getMessage() . "\n";
}
Test yourself
-
What happens when an exception is thrown in a try block?
- The program crashes and stops
- Execution stops and jumps to a matching catch block
- A warning is printed and execution continues
- The try block runs again from the top
Show answer
Execution stops and jumps to a matching catch block — Correct. When an exception is thrown, PHP leaves the try block and jumps to catch.
-
Complete the try/catch skeleton
<?php
____ {
risky();
} catch (\Exception $e) {
echo $e->getMessage() . "\n";
}
Show answer
<?php
try {
risky();
} catch (\Exception $e) {
echo $e->getMessage() . "\n";
}
-
Match the try/catch concepts
- try
- Runs risky code
- catch
- Catches the exception
- finally
- Runs in every case
Next lesson: Throwing exceptions with throw