How to rethrow an InnerException in C# without losing the stack trace?

WBOY
Release: 2023-08-29 09:29:13
forward
554 people have browsed it

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

In C#, throw is a keyword. It is useful to manually throw exceptions during program execution. We can use try-catch blocks as needed to handle these thrown exceptions. .

By using the throw keyword in the catch block, we can rethrow the exception handled in the catch block. Rethrowing exceptions is useful when we want to pass the exception to the caller to handle it the way they want.

The following is an example of using the throw keyword to rethrow an exception to the caller using a try-catch block in C#.

Example

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; } } }
Copy after login

This is how we can rethrow the exception to the caller as needed using the throw keyword in the catch block.

Output

at DemoApplication.Program.Method1() in C:\Users\Koushik\Desktop\Questions\ConsoleApp\Program.cs:line 49 at DemoApplication.Program.Method2() in C:\Users\Koushik\Desktop\Questions\ConsoleApp\Program.cs:line 37 at DemoApplication.Program.Main(String[] args) in C:\Users\Koushik\Desktop\Questions\ConsoleApp\Program.cs:line 24 Null Exception error
Copy after login

The above is the detailed content of How to rethrow an InnerException in C# without losing the stack trace?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!