【问题标题】:Locate where the exception is thrown in a 'try catch' block [duplicate]在“try catch”块中找到引发异常的位置[重复]
【发布时间】:2021-05-21 06:21:41
【问题描述】:

我会举例说明:

        try
        {
            func1();

            func2();

            func3();
        }

        catch (Exception ex)
        {
            Console.WriteLine($"func{i} thrown an exception");
        }

我希望能够让 'i' 保存引发异常的函数号(如果 func2() 导致异常,它应该是 2)。 实现这一目标的最简单方法是什么?

【问题讨论】:

  • 也许你应该看看ex.StackTrace的内容。或者在try之前声明一个变量并设置i = 1; func1(); i = 2; func2(); i = 3; func3();
  • 或为每个函数使用单独的 try 块
  • 异常的位置,最具体的行号、文件和方法都位于消息的StackStrace中,要访问它使用ex.StrackTrace
  • @FranzGleichmann 我只会在第一个或第二个抛出异常的情况下仍然想尝试执行每个函数时才这样做
  • ex 变量本身引用了Exception 对象,该对象有一个StackTrace 属性,可以准确地告诉您抛出异常的位置。这是一个string 值。如果您需要更细粒度的表示,您可以从ex 值创建一个新的StackTrace 对象并检查它。查看副本。

标签: c# exception try-catch


【解决方案1】:

您可以使用 ex.Message 属性。

    static void Main(string[] args)
    {
        try
        {
            func1();
            func2();
            func3();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"func[{ex.Message}] thrown an exception");
        }
    }

    private static void func3()
    {
        throw new Exception("3");
    }

    private static void func2()
    {
        throw new Exception("2");
    }

    private static void func1()
    {
        throw new Exception("1");
    }

【讨论】:

    【解决方案2】:
    CustomeErrorHandler(() => {
      CustomeErrorHandler(() => func1(), "func1 thrown an exception", reThrowError = true);
      CustomeErrorHandler(() => func2(), "func2 thrown an exception", reThrowError = true);
      CustomeErrorHandler(() => func3(), "func3 thrown an exception", reThrowError = true);
    })
    
    
    public static void CustomeErrorHandler(Action a, string error = string.Empty, bool reThrowError = false) 
    {
      try {
       a();
      }
      catch{
       if(!reThrowError) Console.WriteLine(error);
       if(reThrowError) throw new Exception(error);
      }
    }
    
    

    【讨论】:

      【解决方案3】:

      我们可以在 ex.stackTrace 中获取异常详情。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-24
        • 1970-01-01
        • 2011-03-18
        • 1970-01-01
        • 2017-10-03
        • 1970-01-01
        • 2023-03-31
        相关资源
        最近更新 更多