I'm trying to figure out whether the code located after throw new Exception
in PHP is still executed - I've tried it and it didn't seem to output anything but would like to know for sure.
It does, yes.
throw usually causes the function to terminate immediately, so you even if you do put any code after it (inside the same block), it won't execute. This goes for both C++ and C#.
"throw "and "throw new" Exception() In the above case, throws the original exception but resets the stack trace , destroying all stack trace information until your catch block. This means that, it excludes stack information from the point where you called "Throw ex" .
A finally block always executes, regardless of whether an exception is thrown.
No, code after throwing an exception is not executed.
In this code example i marked the lines which would be executed (code flow) with numbers:
try {
throw new Exception("caught for demonstration"); // 1
// code below an exception inside a try block is never executed
echo "you won't read this." . PHP_EOL;
} catch (Exception $e) {
// you may want to react on the Exception here
echo "exception caught: " . $e->getMessage() . PHP_EOL; // 2
}
// execution flow continues here, because Exception above has been caught
echo "yay, lets continue!" . PHP_EOL; // 3
throw new Exception("uncaught for demonstration"); // 4, end
// execution flow never reaches this point because of the Exception thrown above
// results in "Fatal Error: uncaught Exception ..."
echo "you won't see me, too" . PHP_EOL;
See PHP manual on exceptions:
When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with
set_exception_handler()
.
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