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?
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.
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.
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.
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:
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With