使用异常退出PHP应用程序


Using an Exception to Exit PHP Application

我的应用程序有一个注册的关闭函数,这似乎有一些问题,以及我使用带有try/catch的异常来退出应用程序的方法(而不是使用exit()方法,因为FastCGI不喜欢这样)。

我的问题是,如果在try/catch块中抛出另一个不是ExitApp异常的异常,它会导致一些意外结果,最终结果是没有捕获到ExitApp异常。

我在PHP 5.3.6上看到了这一点,现在将在另一个版本上进行测试,但我很好奇是否有人能立即指出这里的错误。

<?php
// Define dummy exception class
class ExitApp extends Exception {}
try {
    // Define shutdown function
    function shutdown() {
        echo "Shutting down...";
        throw new ExitApp;
    }
    register_shutdown_function("shutdown");
    // Throw exception!
    throw new Exception("EXCEPTION!");
} catch(ExitApp $e) {
    echo "Catching the exit exception!";
}
/**
 * Expected Result: Uncaught Exception Error and then "Catching the exit exception!" is printed.
 * Actual Result: Uncaught Exception Error for "Exception" and then Uncaught Exception Error for "ExitApp" even though it's being caught.
 */

您对代码有错误的期望。首先,如果在关闭函数中抛出异常,那么最终总是会出现未捕获的异常——关闭函数在tr/catch块之外调用。

其次,您没有尝试拦截未知异常——您只捕获ExitApp类型。你可能想试试这样的东西:

try {
    //some stuff
} catch(ExitApp $ea) {
    //normal exit, nothing to do here
} catch(Exception $e){
    //something rather unexpected, log it
}

您的shutdown()函数甚至不在try/catch块中,因此它永远不会跳到此异常类型的catch。它将在退出时运行,因此您将不再处于try/catch块中。

在更精神的层面上,尝试/捕捉并不意味着流量控制。我不太清楚你为什么要抛出这个来导致脚本退出,而不仅仅是调用你自己的shutdown()方法。

希望能有所帮助。