PHP

Exceptions

PHP 8.2 • Error Handling

Overview

PHP exceptions provide a structured approach to error handling in OOP programs. Exceptions allow for handling errors gracefully and cleanly, separating error-handling code from regular code.

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

This example demonstrates the basic exception flow with a try/catch block.

Types of Exceptions

1. Built-In Exceptions

  • Exception - Base exception class
  • RuntimeException - Logic errors that cannot be easily caught
  • OutOfBoundsException - Array and iterator out-of-bounds
  • InvalidArgumentException - Argument validation failures

2. Custom Exceptions

Create custom exceptions by extending Exception for specific error handling needs.

<?php
class MyCustomException extends Exception {
    public function __construct($message, $code = 0, Exception $previous = null) {
        parent::__construct($message, $code, $previous);
    }
}
?>

Using try/catch

<?php
try {
    // Code that may throw an exception
    $result = someFunction();
    echo "Result: $result";
} catch (TypeException $e) {
    echo "Caught type error: " . $e->getMessage();
} catch (Exception $e) {
    echo "General error: " . $e->getMessage();
} finally {
    // Always executed
    echo "Execution complete.";
}
?>

Use multiple catch blocks to handle different types of exceptions. The finally block runs regardless of exceptions.

Throwing Exceptions

Throwing in Validation

<?php
function authenticate($username, $password) {
    if (!$username || !$password) {
        throw new InvalidArgumentException("Missing credentials");
    }
}
?>

Best Practices

Use Specific Exceptions

Prefer concrete exception types over generic Exception

Don't Ignore Exceptions

Avoid empty catch blocks. Always handle or log exceptions

Single Responsibility

Each catch block should handle one type of error

Use Finally for Resource Cleanup

Clean up database connections or file handles regardless of outcome

See Also

Error Handling

Traditional error levels and error handling functions

View documentation

ErrorException

Using the ErrorException adapter class

View details
Tip: PHP 8.2 introduces improved static return types and more precise exception handling patterns. Consider using enum exceptions for specific error types.