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.
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.