In this article we are going to discuss Multiple try-catch Exception Handling in C#. There are many blogs, articles are available on the internet regarding Multiple try-catch Exception Handling but in this particular article I will try to explain to you with as much as simplest and realistic examples so you can get a clear idea of the Multiple try-catch Exception Handling use in C#.
Using Multiple try-catch blocks
Multiple catch blocks are used when we are not sure about the exception type that may be generated, so we write different blocks to tackle any type of exception that is encountered. The finally block is the part of the code that has to be executed irrespective of if the exception was generated or not.
All the exception classes in C# are derived from System.Exception class. Let's see the list of C# common exception classes.
Exception | Description |
---|---|
System.DivideByZeroException | handles the error generated by dividing a number with zero. |
System.NullReferenceException | handles the error generated by referencing the null object. |
System.InvalidCastException | handles the error generated by invalid typecasting. |
System.IO.IOException | handles the Input Output errors. |
System.FieldAccessException | handles the error generated by invalid private or protected field access. |
Example
using System;
class Program
{
static void Main()
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
// Catch block for invalid array access
catch (IndexOutOfRangeException e)
{
Console.WriteLine("An Exception has occurred : {0}", e.Message);
}
// Catch block for attempt to divide by zero
catch (DivideByZeroException e)
{
Console.WriteLine("An Exception has occurred : {0}", e.Message);
}
// Catch block for value being out of range
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine("An Exception has occurred : {0}", e.Message);
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
Console.WriteLine("The 'try catch' is finished.Finally block is executed");
}
Console.ReadKey();
}
}
Output