← Back to Chapters

PHP Exception Handling – Multiple Exceptions

⚠️ PHP Exception Handling – Multiple Exceptions

? Quick Overview

PHP supports handling multiple exception types using multiple catch blocks. This allows different errors to be processed in different ways, improving clarity and control.

? Key Concepts

  • Multiple catch blocks can be used with a single try.
  • Specific exception classes should be caught before generic ones.
  • Custom exception classes help categorize errors.

? Syntax & Theory

When multiple exception types exist, PHP checks each catch block in order and executes the first matching one. A general Exception can be used as a fallback.

? Code Example

? View Code Example
// Demonstrating handling multiple exception types in PHP
<?php
class FileException extends Exception {}
class DatabaseException extends Exception {}

try {
$action = "db";
if($action === "file") {
throw new FileException("File error occurred");
} elseif($action === "db") {
throw new DatabaseException("Database error occurred");
}
echo "No exception occurred";
}
catch(FileException $fe) {
echo "Caught FileException: " . $fe->getMessage();
}
catch(DatabaseException $de) {
echo "Caught DatabaseException: " . $de->getMessage();
}
catch(Exception $e) {
echo "Caught general exception: " . $e->getMessage();
}
?>

? Live Output / Explanation

Since $action is set to "db", the DatabaseException is thrown and caught by its corresponding catch block.

? Interactive Explanation

Change the value of $action to "file" or any other value to see different exception handlers in action.

?️ Use Cases

  • Handling file, database, and validation errors separately.
  • Providing user-friendly messages for different error types.
  • Logging critical errors differently from minor ones.

? Tips & Best Practices

  • Always catch specific exceptions before general ones.
  • Use meaningful exception messages.
  • Log unexpected exceptions for debugging.

? Try It Yourself

  • Add another custom exception and handle it.
  • Implement nested try-catch blocks.
  • Log each exception type to a separate file.