0
0
PHPprogramming~5 mins

Multiple catch blocks in PHP

Choose your learning style9 modes available
Introduction

Multiple catch blocks let you handle different errors in different ways. This helps your program respond correctly to each problem.

When you want to handle different types of errors separately.
When you want to show different messages for different problems.
When you want to take different actions depending on the error type.
Syntax
PHP
<?php
try {
    // code that may throw exceptions
} catch (ExceptionType1 $e) {
    // handle ExceptionType1
} catch (ExceptionType2 $e) {
    // handle ExceptionType2
} catch (Exception $e) {
    // handle any other exceptions
}
?>

Each catch block handles one specific type of exception.

The catch blocks are checked in order, so put more specific exceptions first.

Examples
This example catches a specific InvalidArgumentException first, then any other exceptions.
PHP
<?php
try {
    throw new InvalidArgumentException("Invalid argument!");
} catch (InvalidArgumentException $e) {
    echo "Caught invalid argument: " . $e->getMessage();
} catch (Exception $e) {
    echo "Caught general exception: " . $e->getMessage();
}
?>
This example catches RuntimeException separately from InvalidArgumentException.
PHP
<?php
try {
    throw new RuntimeException("Runtime error!");
} catch (InvalidArgumentException $e) {
    echo "Caught invalid argument.";
} catch (RuntimeException $e) {
    echo "Caught runtime exception.";
}
?>
Sample Program

This program throws different exceptions based on input and catches them in separate catch blocks, printing a message for each.

PHP
<?php
function testException($type) {
    try {
        if ($type === 'invalid') {
            throw new InvalidArgumentException("Invalid argument provided.");
        } elseif ($type === 'runtime') {
            throw new RuntimeException("Runtime problem occurred.");
        } else {
            throw new Exception("General error.");
        }
    } catch (InvalidArgumentException $e) {
        echo "Caught InvalidArgumentException: " . $e->getMessage() . "\n";
    } catch (RuntimeException $e) {
        echo "Caught RuntimeException: " . $e->getMessage() . "\n";
    } catch (Exception $e) {
        echo "Caught Exception: " . $e->getMessage() . "\n";
    }
}

testException('invalid');
testException('runtime');
testException('other');
?>
OutputSuccess
Important Notes

Always order catch blocks from most specific to most general exceptions.

If no catch block matches, the exception will cause a fatal error.

Summary

Multiple catch blocks let you handle different errors in different ways.

Put more specific exceptions first, then more general ones.

This helps your program respond clearly and correctly to problems.