Search code examples
c#.netexceptiontry-catch

Difference between Catch(Exception) and Catch(Exception ex)


What is the difference between Catch(Exception) and Catch(Exception ex) . I can see both giving me expected output. Then what is the actual difference ? Which one is recommended ?

Suppose the code is below.

int a = 1, b = 0;
try
{
    int c = a / b;
    Console.WriteLine(c);
}

Which of the below catch block is recommended to use ? What is the actual difference between those ?

catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

OR

catch (Exception)
{
    Console.WriteLine("Oh NO!!");
}

Solution

  • Well, catch(Exception ex) is just the same as catch(Exception) with one difference only: in catch(Exception ex) we have an access to the exception class (error cause) instance. Usually you need an exception class instance to print out the original message:

      try {
        ...
      }
      catch (AppServerException e) {
        Console.WriteLine("Application server failed to get data with the message:");
        Console.WriteLine(e.Message); // <- What's actually got wrong with it
      }
    

    If you don't need the exception class instance, e.g. you plan just to consume the exception, the catch(Exception ex) syntax is excessive and catch(Exception) is prefferable:

      try {  
        c = a / b;
      }  
      catch (DivideByZeroException) {
        c = Int.MaxValue; // <- in case b = 0, let c be the maximum possible int
      }
    

    Finally. Do not catch a general Exception class without re-throwing:

      try {
        int c = a / b;
      }
      catch (Exception) { // <- Never ever do this!
        Console.WriteLine("Oh NO!!");
      }
    

    Do you really want to code "whatever error (green fume from CPU included) had happened just print out 'Oh No' and continue"?

    The pattern with Exception class is something like this:

      tran.Start();
    
      try {
        ...
        tran.Commit();
      }
      catch (Exception) {
        // Whatever had happened, let's first rollback the database transaction
        tran.Rollback();
    
        Console.WriteLine("Oh NO!");
    
        throw; // <- re-throw the exception
      }