PHP自定义异常处理程序需要try{}catch


PHP Does Custom Exception Handler require try {} catch?

我已经编写了以下自定义异常处理程序:

namespace System'Exception;
class Handler extends 'Exception {

    public static function getException($e = null) {
        if (ENVIRONMENT === 0 && is_object($e)) {       
            $message  = "<p>";
            $message .= "Exception: " . $e->getMessage();
            $message .= "<br />File: " . $e->getFile();
            $message .= "<br />Line: " . $e->getLine();
            $message .= "<br />Trace: " . $e->getTrace();
            $message .= "<br />Trace as string: " . $e->getTraceAsString();
            $message .= "</p>";
        } else {
            $message  = '<h1>Exception</h1>';
            $message .= '<p>There was a problem.</p>';
        }
        @require_once('header.php');
        echo $message;
        @require_once('footer.php');
        exit();
    }

    public static function getError($errno = 0, $errstr = null, $errfile = null, $errline = 0) {
        if (ENVIRONMENT === 0) {        
            $message  = "<p>";
            $message .= "Error: " . $errstr;
            $message .= "<br />File: " . $errfile;
            $message .= "<br />Line: " . $errline;
            $message .= "<br />Number: " . $errno;
            $message .= "</p>";
        } else {
            $message  = '<h1>Error</h1>';
            $message .= '<p>There was a problem.</p>';
        }
        @require_once('header.php');
        echo $message;
        @require_once('footer.php');
        exit();
    }   

    public static function getShutdown() {
        $last_error = error_get_last();
        if ($last_error['type'] === E_ERROR) {
            self::getError(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
        }
    }

}

并表示我想使用这个类及其方法以以下方式处理系统生成的所有异常和错误:

set_exception_handler(array("System'Exception'Handler", "getException"));
set_error_handler(array("System'Exception'Handler", "getError"), -1 & ~E_NOTICE & ~E_USER_NOTICE);
register_shutdown_function(array("System'Exception'Handler", "getShutdown"));

我还表示,我不希望错误显示在屏幕和魔杖上报告所有错误:

ini_set('display_errors', 'Off');
error_reporting(-1);

我现在的问题是,我是否仍然需要使用try{}catch(){}语句来捕获任何异常和错误?我知道上面的内容很可能不是防弹的,但到目前为止,通过处理所有未捕获的异常和错误,似乎在没有任何try/catch语句的情况下仍然有效。

此外,使用自定义异常处理程序并让它捕获所有未捕获的异常,而不是通过try{}catch(即性能/安全性等)进行捕获,这有什么缺点吗?

您不必这样做,但您无法恢复-使用try/catch可以为您提供对特定异常做出反应的优势(例如,在some_custom_session_handling()中找不到的文件可能是使用try/cach并在没有会话文件的情况下注销此类用户的好地方)。

所以优点是你有更漂亮的信息。不利的一面是,你对待异常总是一样的。它本身还不错,不应该降低性能或安全性,但它首先忽略了使用异常的要点。

然而,它并不排除在您可能需要的地方使用try/catch,所以我认为这是一个很好的故障转移解决方案,但应该避免作为try/catch替代

正如jderda所说,在使用您的方法时,您错过了异常点:检查代码上层中的任何错误并对其做出反应-停止或处理异常并继续前进。例如,当您想记录所有未捕获的异常时,您的方法很好