7

有没有办法,如何获得当前抛出的异常(如果存在)?

我想减少代码量并为任务应用一些重用,如下所示:

Exception thrownException = null;
try {
    // some code with 3rd party classes, which can throw unexpected exceptions
}
catch( Exception exc ) {
    thrownException = exc;
    LogException( exc );
}
finally {
    if ( null == thrownException ) {
        // some code
    }
    else {
        // some code
    }
}

并用以下代码替换它:

using( ExceptionHelper.LogException() ) {
    // some code with 3rd party classes, which can throw unexpected exceptions
}
using( new ExceptionHelper { ExceptionAction = ()=> /*some cleaning code*/ } ) {
    // some code with 3rd party classes, which can throw unexpected exceptions
}

public class ExceptiohHelper : IDisposable {
    public static ExceptionHelper LogException() {
        return new ExceptionHelper();
    }

    public Action SuccessfulAction {get; set;}
    public Action ExceptionAction {get; set;}

    public void Dispose() {
        Action action;
        Exception thrownException = TheMethodIDontKnow();
        if ( null != thrownException ) {
            LogException( thrownException );
            action = this.ExceptionAction;
        }
        else {
            action = this.SuccessfulAction;
        }

        if ( null != action ) {
            action();
        }
    }
}

这种情况可能吗?

谢谢

4

3 回答 3

11

这个想法是你在 catch 块中处理异常......

也就是说,Exception 是一种引用类型,因此您始终可以在 try 范围之外声明一个 Exception 变量...

Exception dontDoThis;
try
{
    foo.DoSomething();
}
catch(Exception e)
{
    dontDoThis = e;
}
finally
{
    // use dontDoThis...
}
于 2010-01-14T08:43:05.523 回答
5

你怎么看下面的。与其将问题视为“如何获得最后一个异常?”,不如将其更改为“如何运行具有更多控制权的代码片段?”

例如:您可以使用 ActionRunner,而不是 ExceptionHelper。

public class ActionRunner
{
    public Action AttemptAction { get; set; }
    public Action SuccessfulAction { get; set; }
    public Action ExceptionAction { get; set; }

    public void RunAction()
    {
        try
        {
            AttemptAction();
            SuccessfulAction();
        }
        catch (Exception ex)
        {
            LogException(ex);
            ExceptionAction();
        }
    }

    private void LogException(Exception thrownException) { /* log here... */ }
}

假设只有 AttemptAction 在调用之间变化,它至少可以让您重用 SuccessAction 和 ExceptionAction。

var actionRunner = new ActionRunner
{
    AttemptAction = () =>
    {
        Console.WriteLine("Going to throw...");
        throw new Exception("Just throwing");
    },
    ExceptionAction = () => Console.WriteLine("ExceptionAction"),
    SuccessfulAction = () => Console.WriteLine("SuccessfulAction"),
};
actionRunner.RunAction();

actionRunner.AttemptAction = () => Console.WriteLine("Running some other code...");
actionRunner.RunAction();
于 2010-01-14T10:46:56.477 回答
3

如果你想捕捉意外的异常,你应该处理UnhandledException。您应该只在您打算处理的较低级别(不仅仅是记录)捕获异常,否则您应该让它们冒泡并在更高级别被捕获,或者正如我之前在 UnhandledException 方法中提到的那样。

于 2010-01-14T08:47:37.760 回答