Multiple catch blocks with try block in C#

Another important concept related to exception handling using try-catch-finally blocks in C# is the use of multiple catch blocks with a single try block. This is done in order to get more specific information about the exception. To understand this concept better look at the code below

try  {      // Some code here  }  catch (System.IndexOutOfRangeException ex)  {      // Code block 1  }  catch (System.ArrayTypeMismatchException ex)  {      // Code block 2  }  catch (System.NullReferenceException ex)  {      // Code block 3  }  catch (System.DivideByZeroException ex)  {      // Code block 4  }  catch (System.InvalidCastException ex)  {      // Code block 5  }  catch (System.OutOfMemoryException ex)  {      // Code block 6  }  catch (System.StackOverflowException)  {     // Code block 7  }  catch (Exception ex)  {      // Code block 8  }

See how we have used multiple catch blocks with a single try block. The above code is to give you an idea about some important exception classes which are present in C#. You can also inherit from the Exception class and create your own exception class.

Important things to understand

Some important things which you should understand about the above code are

  1. Not all catch block are executed when some exception occurs. Only the best matched catch block will get executed.
  2. From the name of the exception classes their purpose should be easily understood. For example if some null exception is thrown by your code then code block 3 will get executed. If stack overflow exception occurs then code block 7 will get executed. If you try to divide by zero in your code then the DivideByZero exception will be thrown and code block 4 will be executed. But keep in mind only one catch block will be executed during the exception.
  3. If some other type of exception occurs in the code apart from the type of exceptions which are mentioned above then the code block 8 will be get executed. This is because it does not correspond to some specific type of error. It is capable to handling all types of errors because its arguments are of the type Exception.

Only one finally block can be present

Although multiple catch blocks can be used with the try block you can only add one finally block for every try block.  

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp