处理异常并继续执行 [英] Handle exception and continue executing

查看:64
本文介绍了处理异常并继续执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用set_exception_handler()函数定义了自己的异常处理程序.处理程序执行后,我需要脚本才能继续.有什么办法吗?

I define my own exception handler using set_exception_handler() function. After the handler execution, I need the script to continue. Is there any way to do it?

免责声明:我知道try-catch块,但是我需要动态地处理异常.Clazz :: foo()的每次调用都指定了自己的异常,这些异常应由我的处理程序捕获.这就是我不能使用它的原因.

Disclaimer: I know try-catch blocks but I need to process Exceptions dynamicaly. Every calling of Clazz::foo() specifies its own exceptions which should be caught by my handler. That's the reason I can't use it.

示例:

class Clazz {

    private static $exceptions;

    public static function foo(array $exceptions) {
        set_exception_handler(array(__CLASS__, "exception_handler"));
        self::$exceptions = $exceptions;
        throw new RandomException;
        echo "I need this to be printed!";
    }

    public static function exception_handler($exception) {
        // process the exception in my way...
        // if $exception in self::$exceptions than 1, else 2, fi
        restore_exception_handler();
        // continue in some way, like it has never happenned
    }

}

推荐答案

这只是个坏主意.我只是希望您不理解异常的工作原理,而您不是意思是问题.

This is just bad idea. I just hope you don't understand how Exceptions work and you're not meaning the question.

首先,设置异常处理程序... 异常处理程序在将异常传播到主脚本时(实际上不在其中)而被调用,因此您的脚本已完成:

First of all, setting exception handler... Exception handler is called when the exceptions is propagated to main script (actually out of it) and your script is therefore done:

如果在try/catch块中未捕获到异常,则设置默认的异常处理程序.调用exception_handler后,执行将停止.

您应该使用 Xeoncross建议,但是我认为您在调用函数/方法时会遇到抛出异常的问题因此您可以执行以下操作:

You should either use what's Xeoncross suggesting, but I think you have problem with called function/method that is throwing exceptions so you can do this:

class Clazz {

    private static $exceptions;

    public static function foo(array $exceptions) {
        set_exception_handler(array(__CLASS__, "exception_handler"));
        self::$exceptions = $exceptions;
        try {
            throw new RandomException;
        } catch( Exception $e){
            self::exception_handler( $exception);
        }
        echo "I need this to be printed!";
    }

    public static function exception_handler(Exception $exception) {
    }
}

这篇关于处理异常并继续执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆