Diego
Diego

Reputation: 719

Nesting custom Exception example

I don't understand why this code:

class MyException extends Exception {};
try {
    try {
        throw new MyException;
        } catch (Exception $e) {
            echo "1:";
            throw $e;
        } catch (MyException $e) {
            echo "2:";
            throw $e;
        }
}
catch (Exception $e) {
    echo get_class($e);
}

Returns: 1:MyException.

Isn't it supposed to catch the second one MyException and therefore return 2?

I thought with multiple exceptions it looks for the current try/catch first, but it looks like it catches the exception from the first try? or is it because MyException is empty and it uses Exception instead?

Upvotes: 2

Views: 47

Answers (2)

Sam Ivichuk
Sam Ivichuk

Reputation: 1028

Exception here is a base class for your MyException class. Your $e variable has class MyException, so everything is right. If you make:

echo "1:";
var_dump($e);
throw $e;

you will see that $e is object(MyException). You haven't cast types, you just using polymorphism.

All your objects that have type Exception or it's subtypes will be caught in the 1-st block. Code will be executed in first by order block that can apply the exception.

Upvotes: 1

konsolas
konsolas

Reputation: 1091

Catch blocks are processed in the order they appear. Your code for catching MyException will never be called, because all subclasses of Exception are caught in your first catch block.

Upvotes: 1

Related Questions