Checking for exception type in try/catch block in C#

6.8k views Asked by At

I have a rather basic question I've been thinking about.

Refer to the following code snippet that uses a try/catch block:

public void doSomething()  
{  
   try
    {
        doSomethingElse()
    }
    catch (Exception ex)
    {
        if (ex is IndexOutOfRangeException || ex is DivideByZeroException || ex is Exception)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

1) If all I want to do is output the exception message to the console, is it necessary to check in the if clause what type of Exception I'm getting, or can I just do

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

2) It is my understanding that checking the specific exception type should be used if I need to output a defined message to the console instead of using the exception message itself - something along the lines of

...
    catch (Exception ex)
    {
        switch (ex):
        {
            case IndexOutOfRangeException:
                Console.WriteLine("Personalized message #1");               
                break;
            case DivideByZeroException:
                Console.WriteLine("Personalized message #2");               
                break;
            case Exception:
                Console.WriteLine("Personalized message #3");               
                break;
        }
    }
...

Your comments on 1) and 2) are highly appreciated. Thanks for your time.

5

There are 5 answers

0
B Wells On

I recommend not using ex.Message, and instead just using ex.ToString(). As far as I know, that gives you all the information about the exception.

0
Habib On

1) If all I want to do is output the exception message to the console, is it necessary to check in the if clause what type of Exception I'm getting

No there is no need to check each exception type, if you only want to display its message. Simply use Exception.Message property.

2) it is my understanding that checking the specific exception type should be used if I need to output a defined message to the console instead of using the exception message itself

Rather catching base exception and then comparing each for different type, catch specific exception first and then base in the end in each catch block

try
{

}
catch (IndexOutOfRangeException indexOutOfRangeException)
{
      //Specific handling
}
catch (DivideByZeroException divideByZeroException)
{
      //Specific handling
}
catch (Exception ex)
{
      //Exception handling for all other cases
}
0
Sayse On

If all I want to do is output the exception message to the console, is it necessary to check in the if clause what type of Exception I'm getting, or can I just do

No it isn't necessary, yes you can just do

It is my understanding that checking the specific exception type should be used if I need to output a defined message to the console instead of using the exception message itself - something along the lines of..

It should be used to handle exceptions in a different way. But more to the point, you should be using catch to handle exceptions that you don't expect to come across, not to handle program flow (which is what I imagine you are trying to do with your personalised messages). Instead you should have error handling in place that catches the thing that causes the exception before it ever gets there

instead of

catch(IndexOutOfRangeException)

use before hand

if(currentIndex < something.Length)
     //do my thing

If it is from a user input, you can validate currentIndex in this situation in other ways.

0
David Arno On

Point (1) is correct.

Regarding point (2), the switch isn't needed. Instead you can do:

try
{
    doSomethingElse()
}
catch (IndexOutOfRangeException)
{
    Console.WriteLine("Personalized message #1");               
}
catch (DivideByZeroException)
{
    Console.WriteLine("Personalized message #2");               
}
catch (Exception)
{
    Console.WriteLine("Personalized message #3");               
}
0
idipous On

In exception handling go from the most specific exception to the more generic (thus the Exception is last).

You can even rethrow exceptions from within catch and modify the message if you want

The proper way to do this would be:

try{
}catch(IndexOutOfRangeException e){
    LOGGER.errorFormat("This is an error {0}", e.Message);
    LOGGER.debugFormat("More infor on the exception {0}", e.StackTrace);
}catch(DivideByZeroException ex){
    LOGGER.errorFormat("This is an error {0}", ex.Message);
    LOGGER.debugFormat("More infor on the exception {0}", ex.StackTrace);
    throw new Exception("This is custom message");
}...
catch(Exception eex){
}