PHP supports handling multiple exception types using multiple catch blocks. This allows different errors to be processed in different ways, improving clarity and control.
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.
// 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();
}
?>
Since $action is set to "db", the DatabaseException is thrown and caught by its corresponding catch block.
Change the value of $action to "file" or any other value to see different exception handlers in action.