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.
No there is no need to check each exception type, if you only want to display its message. Simply use
Exception.Messageproperty.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