c# - "throw"和 "throw ex"之间有区别吗?

标签 c# .net exception exception-handling

有些帖子询问这两者之间的区别。
(为什么我要提这个...)

但我的问题在某种程度上有所不同,我在另一个错误神级处理方法中调用了“throw ex”。

public class Program {
    public static void Main(string[] args) {
        try {
            // something
        } catch (Exception ex) {
            HandleException(ex);
        }
    }

    private static void HandleException(Exception ex) {
        if (ex is ThreadAbortException) {
            // ignore then,
            return;
        }
        if (ex is ArgumentOutOfRangeException) { 
            // Log then,
            throw ex;
        }
        if (ex is InvalidOperationException) {
            // Show message then,
            throw ex;
        }
        // and so on.
    }
}

如果在 Main 中使用了 try & catch,那么我会使用 throw; 来重新抛出错误。 但是在上面的简化代码中,所有的异常都经过HandleException

HandleException中调用throw ex;是否和调用throw效果一样?

最佳答案

是的,有区别。

  • throw ex 重置堆栈跟踪(因此您的错误看起来源自 HandleException)

  • throw 不会 - 原始违规者将被保留。

     static void Main(string[] args)
     {
         try
         {
             Method2();
         }
         catch (Exception ex)
         {
             Console.Write(ex.StackTrace.ToString());
             Console.ReadKey();
         }
     }
    
     private static void Method2()
     {
         try
         {
             Method1();
         }
         catch (Exception ex)
         {
             //throw ex resets the stack trace Coming from Method 1 and propogates it to the caller(Main)
             throw ex;
         }
     }
    
     private static void Method1()
     {
         try
         {
             throw new Exception("Inside Method1");
         }
         catch (Exception)
         {
             throw;
         }
     }
    

关于c# - "throw"和 "throw ex"之间有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/730250/

相关文章:

java - 在任何情况下(在实践中),在 catch block 中抛出 Exception 是有用的吗?

c# - 为什么在不应该抛出该异常时抛出该异常?

c# - 重写 Equals 和 GetHashCode 不一定会重写相等重载运算符

c# - ASP .NET MVC3 ViewBag 清理字符串

.net - CAML 查询比较 DateTime 与 Eq

C# 相当于 Java PushbackReader 的 unread()

c# - 如何将此 SQL 转换为 LINQ

java - 缺少return语句java编译错误与内部方法异常

c# - 如何识别 "reference assembly"?

c# - 需要解析一个xml字符串