C#重新抛出范围之外的异常

And*_*lon 4 .net c# exception

我完全清楚我要问的不是好的做法......但是:

假设我有一个包含函数的类,我希望始终返回一个值,但是存储可能出现的任何异常以供以后处理.就像是:

public Exception _error { get; set; }

public bool IsValid()
{
    try
    {
        //do something here to cause exception                

        return true;
    }
    catch (Exception ex)
    {
        _error = ex;
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我已经存储了异常,是否可以在保持原始堆栈跟踪和异常类型的同时从外部方法抛出异常?

throw _error; //lose stack trace

throw new Exception("", _error) //lose type
Run Code Online (Sandbox Code Playgroud)

感谢您的回答.

编辑:

感谢一些额外的观点,我意识到以下想法只会带走信息,并没有真正添加或简化情况.再次感谢大家.

在思考了Pieter的回答和评论之后,我现在想知道如果像下面那样创建一个包装器Exception类可能是一个部分解决方案.这会覆盖尽可能多的异常,以使New异常看起来像它的innerexception,包括stacktrace ..脏我知道,但有趣:

public class ExceptionWrapper : Exception
{
    private Exception _innerException;

    public ExceptionWrapper(Exception ex) : base("", ex)
    {
        _innerException = ex;
        this.Source = ex.Source;
        this.HelpLink = ex.HelpLink;
    }

    public override string StackTrace
    {
        get
        {
            return _innerException.StackTrace;
        }
    }

    public override System.Collections.IDictionary Data
    {
        get
        {
            return _innerException.Data;
        }
    }

    public override string Message
    {
        get
        {
            return _innerException.Message;
        }
    }

    public new Exception InnerException
    {
        get
        {
            return _innerException.InnerException;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Pie*_*kel 7

不,这是不可能的.

但是,通常通过将异常包装在新的异常中来解决此问题:

throw new MyException("Wrapper", _error);
Run Code Online (Sandbox Code Playgroud)

这确实维护了堆栈跟踪_error,但是你确实得到了一个新的异常.第二个示例中的解决方案是处理这些情况的正确方法.