Try, Catch, and Finally in PHP
PHP uses exception handling to manage unexpected runtime errors through specific code blocks.
- try – block of code to test
- The catch block executes code to respond to exceptions when they occur.
- The finally block (optional) executes after completion of both try and catch blocks regardless of whether an exception occurred

Syntax
try {
// Code that may throw an exception
} catch (Exception $e) {
// Code that handles the exception
} finally {
// Code that always runs (optional)
}
Example
<?php
try {
echo "Trying...<br>";
throw new Exception("Something went wrong");
} catch (Exception $e) {
echo "Caught: " . $e->getMessage() . "<br>";
} finally {
echo "This will always run.";
}
?>
Overview : Try, Catch & Finally
| Block | Purpose |
|---|---|
| try | Wraps risky code that may throw an exception |
| catch | Catches and handles exceptions |
| finally | Executes code after try/catch, always |
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com