Does 'throw new Exception' require exit()?
No, code after the throw
statement is not executed. Much like return
.
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()
.