6

I'm wondering about something regarding PHP's try, catch statements.

Let's consider the following example.

abstract class ExceptionA extends Exception
{}

class ExceptionB extends ExceptionA
{}

class ExceptionTest
{
    public function example()
    {
        try {
            throw new ExceptionB();
        } catch ( ExceptionB $e ) {
            echo 'ExceptionB was caught';
        } catch ( ExceptionA $e ) {
            echo 'ExceptionA was caught';
        } catch ( Exception $e ) {
            echo 'Exception was caught';
        }
    }
}

All catch statements match the exception. Where the first (ExceptionB) is the closest match.

Will the order of the catch statements be of influence to which one will catch it?

1
  • 2
    It may seem obvious after reading the answer/manual, but I think it's important to note that the order of catch blocks in your example is really the only valid order for that set of exceptions. In any other order at least one of the catch blocks would be unreachable. Jan 10, 2020 at 18:29

1 Answer 1

11

Per the manual:

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block.

You can easily confirm it:

Catching ExceptionB first:

class ExceptionTest
{
    public function example()
    {
        try {
            throw new ExceptionB();
        } catch (ExceptionB $e) {
            echo 'ExceptionB was caught';
        } catch (ExceptionA $e) {
            echo 'ExceptionA was caught';
        } catch (Exception $e) {
            echo 'Exception was caught';
        }
    }
}

(new ExceptionTest())->example();  // Exception B was caught

Demo: https://3v4l.org/htgEg

Catching ExceptionA first and ExceptionB after:

class ExceptionTest
{
    public function example()
    {
        try {
            throw new ExceptionB();
        } catch (ExceptionA $e) {
            echo 'ExceptionA was caught';
        } catch (ExceptionB $e) {
            echo 'ExceptionB was caught';
        } catch (Exception $e) {
            echo 'Exception was caught';
        }
    }
}

(new ExceptionTest())->example();  // Exception A was caught

Demo: https://3v4l.org/J7Xul

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.