Error handling using Try Catch Finally block

In C#, try block followed by one or more catch blocks is used for handling run-time Exceptions (Error).

Below is the example of using try catch block.

+
Code
using System;
 
namespace tryCatchFinally
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int i = 0;
                //error occured at this line.
                int res = 100 / i;
                Console.WriteLine(res);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Following Error occured: \n\t" + ex.Message);
            }
            Console.ReadLine();
        }
    }
}


When we try to run above code,we get Attempted to divide by zero error while dividing 100 by 0 and from that line, control directly goes to catch block without executing next line of code in try block, and print an error at console.

By using try-catch block, we can show a user friendly message to users of our application.

We can declare more than one catch block for one try block. Depending on the error occurred in try block, corresponding catch block gets executed. See below example for the same.

+
Code

using System;
 
namespace tryCatchFinally
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int i = 0;
 
                int[] j = new int[2];
 
                j[0] = 1;
                j[1] = 2;
                //You can't add 3rd element in array j, as its size is 2. We get Index out of range exception here.
                j[2] = 3;
 
                foreach (int m in j)
                {
                    Console.WriteLine(m);
                }
 
                //error occured at this line.
                int res = 100 / i;
                Console.WriteLine(res);
            }
            catch (IndexOutOfRangeException ex)
            {
                Console.WriteLine("Index of array j is out of range. You can add only 2 items in it.");
            }
            catch (DivideByZeroException ex)
            {
                Console.WriteLine("You can't devide a number by zero");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Following Error occured: \n\t" + ex.Message);
            }
            Console.ReadLine();
        }
    }
}

In the above code, we have declared 3 catch block, 1st is handling Index out of range exception, 2nd handling Divide by zero exception and 3rd handling errors other than these errors (all errors). if we execute above code, as int array j has size 2, if we try to add 3rd element in it, we get index out of range exception there and control directly goes to 1st catch block printing error Index of array j is out of range. You can add only 2 items in it on console. If we get divide by zero error then control goes to 2nd catch block and if error other than these 2 errors gets occurred then 3rd catch block gets executed.

We have another block in our try catch block, finally block, which gets executed every time when control left from try/catch block irrespective of error occurred or not. So we can do any cleanup resource activities, closing connection activity in finally block.
Below is the syntax for the same. We can write try-finally block as well (excluding catch block).

+
Code

try
{
                               
}
catch (Exception ex)
{
                
}
finally
{
 
}

No comments :