PHP try-catch
In this page:
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 {
$result = 10 / 0;
} catch (DivisionByZeroError $e) {
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 {
throw new Exception("Something failed", 42);
} catch (Exception $e) {
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
function checkAge($age) {
if ($age < 0) {
throw new Exception("Age cannot be negative");
}
return $age;
}
try {
checkAge(-5);
} catch (Exception $e) {
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 {
throw new InvalidArgumentException("Bad input");
} catch (InvalidArgumentException $e) {
echo "Specific: " . $e->getMessage();
} catch (Exception $e) {
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 {
echo "Trying...\n";
throw new Exception("Failed");
} catch (Exception $e) {
echo "Caught: " . $e->getMessage() . "\n";
} finally {
echo "Cleanup always runs";
}
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: