Try Catch Finally is the  building block of exception handling in c#. ‘Try’ block keeps the code which may through exception at runtime. The ‘catch’ block handle the exception if try block rais error and ‘finally’ block executes always exception is raised or not. A try block may have multiple catch blocks.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exception_Handling_Example
{
    class Program
    {
        static void Main(string[] args)
        {
            label:
            // Try block: The code which may raise exception at runtime
            try
            {
                int num1, num2;
                decimal result;
                Console.WriteLine("Divide Program. You Enter 2 number and we return result");
                Console.WriteLine("Enter 1st Number: ");
                num1 = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Enter 2nd Number: ");
                num2 = Convert.ToInt32(Console.ReadLine());
                result =(decimal)num1 / (decimal)num2;
                Console.WriteLine("Divide : " + result.ToString());
                Console.ReadLine();
            }
           //Multiple Catch block to handle exception
            catch (DivideByZeroException dex)
            {
                Console.WriteLine("You have Entered 0");
                Console.WriteLine("More Details about Error: \n\n" + dex.ToString() + "\n\n");
                goto label;
            }
            catch (FormatException fex)
            {
                Console.WriteLine("Invalid Input");
                Console.WriteLine("More Details about Error: \n\n" + fex.ToString() + "\n\n");
                goto label;
            }
            //Parent Exception: Catch all type of exception
            catch (Exception ex)
            {
                Console.WriteLine("Othe Exception raised" + ex.ToString() + "\n\n");
                goto label;
            }
           //Finally block: its always executed
            finally
            {
                Console.WriteLine("For Continue Press Enter and for Exit press Ctrl + c");
                Console.ReadLine();
            }
        }
    }
}

Output Explain

Output 1

First input : 5
Second input : 2

It will not through any exception and shows output. finally block executed at the end.

Output 2

First input : 5
Second input : 0

It will through DivideByZeroException and handled by DivideByZeroException catch block.

catch (DivideByZeroException dex)
  {
     Console.WriteLine("You have Entered 0");
     Console.WriteLine("More Details about Error: \n\n" + dex.ToString() + "\n\n");
     goto label;
  }

Leave a Reply

Your email address will not be published. Required fields are marked *