HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Try / Catch / Finally

In PHP, structured exception handling is achieved through three keywords: try, catch, and finally. These blocks allow you to write code that can handle unexpected errors without crashing your entire application.


The Try-Catch Structure

The basic idea is to "try" a block of code. If an exception occurs within that block, it is "caught" by a catch block, where you can handle the error gracefully.

<?php
    try {
        // Code that may throw an exception
    } catch (Exception $e) {
        // Code that runs if an exception is thrown
    }
?>

1. The try Block

The try block contains the code that you want to execute, but which might trigger an error. If an exception is thrown inside this block, the remaining code in the block is skipped, and execution jumps immediately to the catch block.

Note: A try block cannot stand alone; it must be followed by at least one catch block or a finally block.

2. The catch Block

The catch block is where you handle the exception. It defines the type of exception it can catch and assigns the exception object to a variable (usually $e or $exception).

<?php
    function divide($dividend, $divisor) {
        if($divisor == 0) {
            throw new Exception("Division by zero error!");
        }
        return $dividend / $divisor;
    }

    try {
        echo divide(10, 0);
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage();
    }
?>
Tip: You can use multiple catch blocks to handle different types of exceptions in different ways.

3. The finally Block

The finally block is optional, but very useful. It contains code that will always run, regardless of whether an exception was thrown or caught. This is typically used for "cleanup" tasks, such as closing database connections or deleting temporary files.

<?php
    try {
        echo divide(10, 2);
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage();
    } finally {
        echo "This will always execute.";
    }
?>
Key Fact: The finally block executes even if the try or catch blocks contain a return statement.

Multiple Catch Blocks

In complex applications, you might want to handle different errors differently. You can stack multiple catch blocks for this purpose.

<?php
    try {
        // Some complex logic
        if (!file_exists("data.txt")) {
            throw new Exception("File not found!");
        }
    } catch (InvalidArgumentException $e) {
        echo "Argument Error: " . $e->getMessage();
    } catch (Exception $e) {
        echo "General Error: " . $e->getMessage();
    }
?>

Summary of Exception Handling

  • try — Wraps the code that might throw an exception.
  • catch — Defines how to respond to a specific exception.
  • finally — Executes code regardless of the outcome (always runs).
  • throw — Used to manually trigger an exception when a condition is met.
Remember: Good exception handling improves the user experience by preventing "white screen of death" errors and providing helpful feedback.