← Back to Chapters

PHP Exception Handling — Try, Catch, Finally

? PHP Exception Handling — Try, Catch, Finally

? Quick Overview

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.

? Key Concepts

  • try contains code that may throw an exception
  • catch handles the exception if one occurs
  • finally always executes, regardless of success or failure

? Syntax & Theory

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.

? View Code Example
// 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.";
    }
}
?>

? Output Explanation

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.

? Interactive Concept Flow

Execution order: Try ➜ Catch (if error) ➜ Finally (always)

Click 'Run Logic' to see the process...

? Use Cases

  • Closing database connections
  • Releasing file handles
  • Cleaning temporary resources
  • Ensuring consistent application behavior

? Tips & Best Practices

  • Use finally for guaranteed cleanup actions
  • Keep try blocks short and focused
  • Always validate resources before closing them

? Try It Yourself

  • Open multiple files and close them using one finally block
  • Wrap a database connection inside try-catch-finally
  • Add multiple catch blocks for different exception types