简体   繁体   English

创建c#异常而不抛出它

[英]Create c# exception and not throw it

Is there a way better than what I'll have written below to get an exception properly set like when thrown? 有没有一种方法可以比抛出异常时正确设置的异常情况好得多?

try {
throw new Exception("Blah");
}
catch (Exception exe) {
Assert.NotNull(exe.StackTrace);
DoSomeWork(exe);
// throw;
}

The short answer is : NO. 最简洁的答案是不。

The System.Exception properties are filled in when it is thrown : 抛出 System.Exception属性时,它会被填充:

By default, the stack trace is captured immediately before an exception object is thrown. 默认情况下,将在引发异常对象之前立即捕获堆栈跟踪。 Use Environment.StackTrace to get stack trace information when no exception is being thrown. 没有引发异常时,请使用Environment.StackTrace获取堆栈跟踪信息。

So if you really need an exception object in the state it is after being thrown you have no other good way but to throw and catch it. 因此,如果您确实需要处于exception状态的exception对象,那么在抛出该exception对象之后,您别无其他方法只能抛出并捕获它。

Still do not drop off the main question: do you really need the exception object? 仍然不放弃主要问题:您是否真的需要异常对象?

If you've got a method that has System.Exception as an input parameter and you need a StackTrace inside, think of these possible solutions: 如果您有一个将System.Exception作为输入参数的方法,并且需要一个StackTrace,请考虑以下可能的解决方案:

  1. Method overload with an optional StackTrace input parameter. 使用可选的StackTrace输入参数的方法重载。
  2. A successor of System.Exception with a hiding StackTrace property which memorizes the StackTrace when the object is created not thrown. System.Exception的后继者,具有一个隐藏的StackTrace属性,该属性在创建对象时不抛出该异常,用于存储StackTrace。
  3. As the last resort you could make an extension method for the System.Exception class which "populates" an instance of the System.Exception: 作为最后的选择,您可以为System.Exception类创建一个扩展方法,该方法“填充” System.Exception的实例:

     private void MyCode() { Exception exe = new Exception("Blah"); exe.Populate(); DoSomeWork(exe); } public static void Populate(this System.Exception source) { try { throw source; } catch { } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM