2012-06-26 99 views
17

我试图弄清楚PHP中的throw new Exception后面的代码是否仍然执行 - 我已经尝试过了,它似乎没有输出任何内容,但是很想知道。'抛出新的异常'需要退出()?

+0

我不知道什么是异常的一点,如果它不会导致堆栈展开(直到适当的条件,例如'catch',阻止它展开堆栈)... – 2012-06-26 19:50:12

+8

_When exception is抛出后,语句后面的代码将不会执行,并且PHP将尝试查找第一个匹配的catch块。如果没有捕获到异常,除非使用set_exception_handler()._ [来自文档](http:// php。)定义了一个处理程序,否则将发出一个PHP致命错误,并带有“Uncaught Exception ...”消息。净/手动/ EN/language.exceptions.php) –

回答

32

不,不执行抛出异常后的代码。

在此代码示例我用数字标记,其将被执行的行(码流):

try { 
    throw new Exception("caught for demonstration");     // 1 
    // code below inside the 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!" . 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; 

参见PHP manual on exceptions

当一个异常被抛出后的语句,代码将不会被执行,并且PHP将尝试查找第一个匹配的catch块。如果未捕获到异常,除非已使用set_exception_handler()定义了处理程序,否则会发出PHP致命错误,并显示“Uncaught Exception ...”消息。

3

不,不会执行throw语句后的代码。很像return