PHP Exception Handling

Managing exceptions with try-catch blocks

🎯 What is PHP Exception?

PHP Exceptions provide a modern way to handle errors using try-catch blocks. When an error occurs, an exception is thrown and caught, allowing graceful error handling without stopping script execution abruptly.


<?php
try {
    throw new Exception("Something went wrong!");
} catch(Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>
                                    

Output:

Error: Something went wrong!

Exception Components

🔄

try

Code that might throw exception

<?php
try {
    // risky code
}
?>
🎣

catch

Handles thrown exceptions

<?php
catch(Exception $e) {
    // handle error
}
?>
🚀

throw

Triggers an exception

<?php
throw new Exception("Error!");
?>
✅

finally

Always executes after try-catch

<?php
finally {
    // cleanup code
}
?>

🔹 Basic Try-Catch

The try-catch block is the foundation of exception handling. Place potentially problematic code inside try, and handle any exceptions in catch. This prevents your script from crashing and allows you to respond appropriately to errors.

<?php
function divide($a, $b) {
    if($b == 0) {
        throw new Exception("Cannot divide by zero!");
    }
    return $a / $b;
}

try {
    echo divide(10, 0);
} catch(Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>

Output:

Error: Cannot divide by zero!

🔹 Multiple Catch Blocks

Handle different exception types with multiple catch blocks. This allows specific error handling for different situations. PHP checks each catch block in order and executes the first one that matches the thrown exception type.

<?php
try {
    $age = -5;
    if($age < 0) {
        throw new InvalidArgumentException("Age cannot be negative!");
    }
} catch(InvalidArgumentException $e) {
    echo "Invalid input: " . $e->getMessage();
} catch(Exception $e) {
    echo "General error: " . $e->getMessage();
}
?>

Output:

Invalid input: Age cannot be negative!

🔹 Finally Block

The finally block executes regardless of whether an exception was thrown or caught. Use it for cleanup operations like closing database connections or file handles. This ensures critical cleanup code always runs, maintaining resource integrity.

<?php
try {
    echo "Opening file...\n";
    throw new Exception("File error!");
} catch(Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
} finally {
    echo "Closing file...";
}
?>

Output:

Opening file...
Error: File error!
Closing file...

🔹 Custom Exception Class

Create custom exception classes by extending the base Exception class. This allows you to add custom properties and methods specific to your application's error handling needs, making your code more organized and maintainable.

<?php
class CustomException extends Exception {
    public function errorMessage() {
        return "Custom Error: " . $this->getMessage();
    }
}

try {
    throw new CustomException("Something failed!");
} catch(CustomException $e) {
    echo $e->errorMessage();
}
?>

Output:

Custom Error: Something failed!

🔹 Exception Methods

Exception objects provide useful methods to get error details. getMessage() returns the error message, getCode() returns the error code, getFile() shows where the error occurred, and getLine() indicates the line number.

<?php
try {
    throw new Exception("Test error", 100);
} catch(Exception $e) {
    echo "Message: " . $e->getMessage() . "\n";
    echo "Code: " . $e->getCode() . "\n";
    echo "File: " . $e->getFile() . "\n";
    echo "Line: " . $e->getLine();
}
?>

Output:

Message: Test error
Code: 100
File: /var/www/html/test.php
Line: 3

🔹 Re-throwing Exceptions

Sometimes you need to catch an exception, perform some action, then re-throw it for higher-level handling. This is useful for logging errors locally while still allowing parent code to handle the exception appropriately.

<?php
try {
    try {
        throw new Exception("Inner error");
    } catch(Exception $e) {
        echo "Caught: " . $e->getMessage() . "\n";
        throw $e; // Re-throw
    }
} catch(Exception $e) {
    echo "Re-caught: " . $e->getMessage();
}
?>

Output:

Caught: Inner error
Re-caught: Inner error

🧠 Test Your Knowledge

Which keyword is used to trigger an exception?