- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to rethrow InnerException without losing stack trace in C#?
In c#, the throw is a keyword and it is useful to throw an exception manually during the execution of the program and we can handle those thrown exceptions using try−catch blocks based on our requirements.
By using throw keyword in the catch block, we can re-throw an exception that is handled in the catch block. The re-throwing an exception is useful when we want to pass an exception to the caller to handle it in a way they want.
Following is the example of re−throwing an exception to the caller using throw keyword with try-catch blocks 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; } } }
This is how we can re-throw an exception to the caller using throw keyword in catch block based on our requirements.
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
Advertisements
To Continue Learning Please Login
Login with Google