PHP try-catch
In this page:
try {
// code that might fail
throw new Exception("message");
} catch (Exception $e) {
echo $e->getMessage();
} finally {
// always runs
}
Introduction to try-catch
A try-catch block lets you contain risky operations -- like a database call that might fail -- inside the try section, while the catch section defines what happens if something actually goes wrong, instead of the whole script crashing.
Example: Introduction to try-catch
<?php
// Try running this block; jump to `catch` if it throws
try {
// Declare `$result`, set to `10 / 0`
$result = 10 / 0;
// Catch DivisionByZeroError $e
} catch (DivisionByZeroError $e) {
// Print `"Caught: " . $e->getMessage()` to the output
echo "Caught: " . $e->getMessage();
}
?>
Login to try C/C++/Java/PHP code in the editor
The Exception Object
Every caught Exception object carries useful diagnostic details -- its message, an optional error code, and the file and line where it was thrown -- which you can inspect to decide how to respond or what to log.
Example: The Exception Object
<?php
// Try running this block; jump to `catch` if it throws
try {
// Throw a new `Exception` with message `"Something failed", 42`
throw new Exception("Something failed", 42);
// Catch Exception $e
} catch (Exception $e) {
// Print `$e->getMessage() . " (code: " . $e->getCode() . ")"` to the output
echo $e->getMessage() . " (code: " . $e->getCode() . ")";
}
?>
Login to try C/C++/Java/PHP code in the editor
Throwing Exceptions
The throw keyword is how your own code signals a problem, immediately halting normal execution and jumping to the nearest matching catch block, similar to how a runtime error would.
Example: Throwing Exceptions
<?php
// Define the function `checkAge` taking `$age`
function checkAge($age) {
// Check whether `$age < 0`
if ($age < 0) {
// Throw a new `Exception` with message "Age cannot be negative"
throw new Exception("Age cannot be negative");
}
// Return `$age` from this function
return $age;
}
// Try running this block; jump to `catch` if it throws
try {
// Call `checkAge(-5)`
checkAge(-5);
// Catch Exception $e
} catch (Exception $e) {
// Print `$e->getMessage()` to the output
echo $e->getMessage();
}
?>
Login to try C/C++/Java/PHP code in the editor
Multiple catch Blocks
When you expect several distinct kinds of failure, stacking multiple catch blocks lets you handle each one differently -- just order them from most specific exception type to most general, since PHP checks them top to bottom.
Example: Multiple catch Blocks
<?php
// Try running this block; jump to `catch` if it throws
try {
// Throw a new `InvalidArgumentException` with message "Bad input"
throw new InvalidArgumentException("Bad input");
// Catch InvalidArgumentException $e
} catch (InvalidArgumentException $e) {
// Print `"Specific: " . $e->getMessage()` to the output
echo "Specific: " . $e->getMessage();
// Catch Exception $e
} catch (Exception $e) {
// Print `"General: " . $e->getMessage()` to the output
echo "General: " . $e->getMessage();
}
?>
Login to try C/C++/Java/PHP code in the editor
The finally Block
Code inside a finally block always runs, whether the try succeeded or an exception was caught, which makes it the natural place for cleanup like closing a file handle or database connection.
Example: The finally Block
<?php
// Try running this block; jump to `catch` if it throws
try {
// Print "Trying...\n" to the output
echo "Trying...\n";
// Throw a new `Exception` with message "Failed"
throw new Exception("Failed");
// Catch Exception $e
} catch (Exception $e) {
// Print "Caught: " . $e->getMessage() . "\n" to the output
echo "Caught: " . $e->getMessage() . "\n";
// Runs no matter what, whether or not an exception was thrown
} finally {
// Print "Cleanup always runs" to the output
echo "Cleanup always runs";
}
?>
Login to try C/C++/Java/PHP code in the editor
- Catching an exception and leaving the catch block empty, which hides the error completely.
- Putting a general
catch (Exception $e)before specific catch blocks, so the specific ones never run. - Expecting
try/catchto catch ordinary warnings and notices, which are not exceptions unless you convert them.
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: