The try-catch-finally structure in PHP provides a clean way to handle runtime errors using exceptions. It allows error-prone code to be tested, errors to be handled gracefully, and cleanup code to always run.
PHP executes code inside the try block first. If an exception is thrown, execution jumps to the catch block. The finally block runs in all cases, making it ideal for resource cleanup.
// Demonstrating try, catch, and finally in PHP
<?php
try {
$file = fopen("sample.txt", "r");
if (!$file) {
throw new Exception("Unable to open the file.");
}
echo "File opened successfully.";
}
catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
finally {
if (isset($file) && $file) {
fclose($file);
echo "<br>File closed in finally block.";
}
}
?>
If the file opens successfully, a success message is displayed. If it fails, the error message from the exception is shown. In both cases, the file is safely closed inside the finally block.
Execution order: Try ➜ Catch (if error) ➜ Finally (always)