posted 8/17/2011 by Hajan Selmani
Using try catch finally blocks is very recommended practice in order to handle exceptions properly. There are many other benefits of using this, however, the focus of this post is to show how you can handle multiple exceptions at same time.
When you deal with exceptions, the general rule is that you go from the more specific to the more general one.
One example:
string strName = "hajan"; try { int number = Convert.ToInt32(strName); } catch (InvalidCastException ex) { Console.WriteLine("Invalid Cast exception thrown: " + ex.Message); } catch (FormatException ex) { Console.WriteLine("Format exception thrown: " + ex.Message); } catch (Exception ex) { Console.WriteLine("Exception thrown: " + ex.Message); }
If you run this on console, it should print:
Format exception thrown: Input string was not in a correct format.
However, this is also a General exception since all specific exception types inherit from the Exception. Why if we want to run the code in catch(Exception ex) as well, so two catch blocks should be executed, which is not really possible.
So, in order to achieve this, to handle and throw multiple exceptions at once, you may want to consider the following way:
try { int number = Convert.ToInt32(strName); } catch (Exception ex) { if (ex is NullReferenceException) { Console.WriteLine("Null Reference Exception thrown!"); } if (ex is FormatException) { Console.WriteLine("Format exception thrown!"); } if (ex is InvalidCastException) { Console.WriteLine("Invalid Cast Exception thrown!"); } if (ex is OverflowException) { Console.WriteLine("Overflow Exception thrown!"); } if (ex is Exception) { Console.WriteLine("General Exception thrown!"); } }
As you can see, we catch the general Exception ex, and then cast it to the specific exception type. So, if it cames the exception to be two of the specific type exceptions, all code blocks inside if that satisfy the condition will run.
I came into idea to write about this after seeing a suggestion for Visual Studio.NET improvements here, which is actually not really related to Visual Studio but more to C# and C# compiler. So, this is temporary solution for handling multiple exceptions in same time. Of course, you can combine them in AND or OR conditions together to handle different scenarios when an Exception occurs.
Hope this was useful.
Regards,Hajan
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18