在catch()中抛出新异常

时间:2013-09-18 23:40:49

标签: c# exception-handling

我正在尝试捕获异常,向其添加信息,并为调用模块抛出一个新的(增强的)异常。

示例:

    void CallingMethod()
    {
        try
        {
            doStuff();
        }
        catch(Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    void doStuff()
    {
        try
        {
            // do something here that may throw an error
        }
        catch(Exception e)
        {
            Exception e2 = new Exception("new added info", e);
            throw e2;
        }
        finally()
        {
            // cleanup
        }
    }

但是当错误发生并写入控制台时,原始错误不是包含字符串“new added info”的新错误。

这是预期的吗?我应该如何抛出 新的 错误?

1 个答案:

答案 0 :(得分:2)

考虑这个程序:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication20
{
  class Program
  {
    static void Main( string[] args )
    {
      DoSomething() ;
      return ;
    }
    static void DoSomething()
    {
      try
      {
        DoSomethingThatFails() ;
      }
      catch( Exception e )
      {
        throw new InvalidOperationException( "This is the wrapper exception" , e ) ;
      }
    }
    static int DoSomethingThatFails()
    {
      int x = 3 ;
      int y = 0 ;
      int z = x / y ; // can you say "divide by zero"?
      return z ;
    }
  }
}

这是写入控制台的内容:

Unhandled Exception: System.InvalidOperationException: This is the wrapper exception ---> System.DivideByZeroException: Attempted to divide by zero.
   at ConsoleApplication20.Program.DoSomethingThatFails() in ...\Program.cs:line 32
   at ConsoleApplication20.Program.DoSomething() in ...\Program.cs:line 21
   --- End of inner exception stack trace ---
   at ConsoleApplication20.Program.DoSomething() in ...\Program.cs:line 25
   at ConsoleApplication20.Program.Main(String[] args) in ...\Program.cs:line 14

您会注意到第一行包含外部异常及其消息(InvalidOperationExceptionThis is the wrapper exception),后跟箭头(--->),后跟内部异常( DivideByZeroExceptionAttempted to divide by zero.)。

接下来的两行是内部异常的堆栈跟踪,后跟一个标记,指示内部异常堆栈跟踪的结束。然后,您将获得外部例外的堆栈跟踪。

所有信息都在那里,你只是没有看到它。