如何在 C# 中重新抛出 InnerException 而不丢失堆栈跟踪?

如何在 C# 中重新抛出 InnerException 而不丢失堆栈跟踪?

在c#中,throw是一个关键字,在程序执行过程中手动抛出异常很有用,我们可以根据需要使用try-catch块来处理这些抛出的异常。

通过在 catch 块中使用 throw 关键字,我们可以重新抛出在 catch 块中处理的异常。当我们想要将异常传递给调用者以按照他们想要的方式处理它时,重新抛出异常非常有用。

以下是使用 throw 关键字向调用者重新抛出异常的示例在 C# 中使用 try-catch 块。

示例

class Program{ static void Main(string[] args){ try{ Method2(); } catch (System.Exception ex){ System.Console.WriteLine($"{ex.StackTrace.ToString()} {ex.Message}"); } Console.ReadLine(); } static void Method2(){ try{ Method1(); } catch (System.Exception){ throw; } } static void Method1(){ try{ throw new NullReferenceException("Null Exception error"); } catch (System.Exception){ throw; } } }登录后复制

输出

at DemoApplication.Program.Method1() in C:UsersKoushikDesktopQuestionsConsoleAppProgram.cs:line 49 at DemoApplication.Program.Method2() in C:UsersKoushikDesktopQuestionsConsoleAppProgram.cs:line 37 at DemoApplication.Program.Main(String[] args) in C:UsersKoushikDesktopQuestionsConsoleAppProgram.cs:line 24 Null Exception error登录后复制