开发者

c# - combine 2 statements in a catch block into one

Does anybody know if it's possible to write the code in the catch block below as a single statement? I haven't been able to come up with a way, and was just curious if there was one.

IMPORTANT: the stack trace must be preserved.

    catch (Exception e)
    {
       开发者_如何学编程 if (e is MyCustomException)
        {
            // throw original exception
            throw;
        }

        // create custom exception
        MyCustomException e2 =
            new MyCustomException(
                "An error occurred performing the calculation.", e);
        throw e2;
    }


What about:

catch (MyCustomException)
{
   throw;
}
catch (Exception ex)
{
   throw new MyCustomException(ex);
}


catch (Exception e)
{
   if (e is MyCustomException) throw;

   throw new MyCustomException("An error occurred performing the calculation.", e);
}

I think that's about as terse as it gets, I think.

This immediately throws MyCustomException up the stack (which is what you're accomplishing with throw; in your question) while throwing a MyCustomException to wrap other Exception types encountered in execution.

Alternatively, you can just do:

catch (Exception e)
{
   throw new MyCustomException("An error occurred performing the calculation.", e);
}

and in the case where MyCustomException was caught, you'll have a MyCustomException in e.InnerException where is e a MyCustomException at the next level of the stack OR you'll have a System.Exception in the cases that MyCustomException is not what was caught.


I know that this isn't answering your original question, however its worth noting that you should be careful when using throw - although miles better than throw ex, there may still be circumstances where using throw does not preserve the stack trace. See:

http://weblogs.asp.net/fmarguerie/archive/2008/01/02/rethrowing-exceptions-and-preserving-the-full-call-stack-trace.aspx


It is actually possible.

However, the stacktrace will contain additional entries:

public static class ExceptionHelper
{
    public static void Wrap<TException>(Action action, Func<Exception, TException> exceptionCallback)
        where TException : Exception
    {
        try
        {
            action();
        }
        catch (TException)
        {
            throw;
        }
        catch (Exception ex)
        {
            throw exceptionCallback(ex);
        }
    }
}
//Usage:
ExceptionHelper.Wrap(() => this.Foo(), inner => new MyCustomException("Message", inner));


Would this work?

        catch (Exception e)
        {
            throw e.GetType() == typeof(MyCustomException) ? e : new MyCustomException("An error occurred performing the calculation.", e);
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜