Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does 'throw new Exception' require exit()?

Tags:

exception

php

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.

like image 732
Spencer Mark Avatar asked Jun 26 '12 19:06

Spencer Mark


People also ask

Does throw exception exit function?

It does, yes.

Does throw exit the function C++?

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#.

What does throw new exception do?

"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" .

Does finally execute after throwing exception?

A finally block always executes, regardless of whether an exception is thrown.


1 Answers

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().

like image 191
Kaii Avatar answered Oct 02 '22 13:10

Kaii