Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP try, catch precedence and inheritance

Tags:

php

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?

like image 201
jrswgtr Avatar asked Jan 10 '20 17:01

jrswgtr


People also ask

Does PHP have try catch?

The primary method of handling exceptions in PHP is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can "try" to execute a block of code, and "catch" any PHP exceptions that are thrown.

Can we use nested try catch in PHP?

Try-catch blocks in PHP can be nested up to any desired levels and are handled in reverse order of appearance i.e. innermost exceptions are handled first.

Can we use catch () without passing arguments in it?

Some exception can not be catch(Exception) catched. Below excecption in mono on linux, should catch without parameter. Otherwise runtime will ignore catch(Exception) statment.


1 Answers

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

like image 53
Jeto Avatar answered Nov 15 '22 07:11

Jeto