1.使用throw和throw ex抛出异常的区别

通常,我们使用try/catch/finally语句块来捕获异常,那么在抛出异常的时候,使用throw和throw ex有什么区别呢?

假如,按顺序调用以下几个方法:

  • 在Main方法中调用Method1方法,try/catch捕获异常
  • 在Method1方法中调用Method2方法,try/catch捕获异常
  • 在Method2方法中故意抛出异常,try/catch捕获异常

使用throw抛出异常:

static void Main(string[] args)
        {
            try
            {
                Method1();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace.ToString());
                
            }
            Console.ReadKey();
        }
        static void Method1()
        {
            try
            {
                Method2();
            }
            catch (Exception ex)
            {          
                throw;
            }
        }
        static void Method2()
        {
            try
            {
                throw new Exception("来自方法2的异常");
            }
            catch (Exception ex)
            {                
                throw;
            }
        }

结果表明:使用throw抛异常,会把发生在Method2方法、Method1方法和Main方法中的异常全部抛了出来。 

如果在Method1方法中,改用throw ex抛出异常,则只会把Method1方法和Main方法中的异常抛出来。

总结:获取最完整的StackTrace信息,请使用throw抛出异常,这样可以知道异常到底来自哪个方法。

 

可参考:Is there a difference between “throw” and “throw ex”?

 

2.异常机制及throw与throws的区别

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-09
  • 2021-09-02
  • 2021-10-16
猜你喜欢
  • 2021-07-28
  • 2021-07-21
  • 2022-12-23
  • 2021-04-30
  • 2021-05-27
  • 2021-08-28
  • 2021-06-20
相关资源
相似解决方案