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

Updated on: 05-Nov-2020

892 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements