Try Catch Finally in c#

In this Section you will learn:
  • What is try catch block in c#?
  • What is finally block in c#?
  • Try catch programming example

Try Catch Finally

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

Programming Example of Try Catch Finally Block

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exception_Handling
{
    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: it always executes

            finally
            {
                Console.WriteLine("Finally Block: 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 raise any exception and shows output. finally block executed at the end.
Divide Program. You Enter 2 number and we return result
Enter 1st Number:
5
Enter 2nd Number:
2
Divide : 2.5Finally Block: For Continue Press Enter and for Exit press Ctrl + c__
 
Output 2
First input : 5
Second input : 0
It will raise 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;
  }

Divide Program. You Enter 2 number and we return result
Enter 1st Number:
5
Enter 2nd Number:
0
You have Entered 0

More Details about Error:System.DivideByZeroException: Attempted to divide by zero. at System.Decimal.FCallDivide(Decimal& d1, Decimal& d2) at System.Decimal.op_Division(Decimal d1, Decimal d2) at Exception_Handling.Program.Main(String[] args) in c:\Users\Prashant\Docume nts\Visual Studio 2012\Projects\advancecsharp\Exception Handling\Exception Handl ing\Program.cs:line 26Finally Block: For Continue Press Enter and for Exit press Ctrl + c __
 
Output 3
First input : 4
Second input : k

We have entered second input as an alphabet and we all know that a number can't be divided by alphabet so It will raise FormatException and handled by FormatException catch block.

catch (FormatException fex)
  {
    Console.WriteLine("Invalid Input");
    Console.WriteLine("More Details about Error: \n\n" + fex.ToString() + "\n\n");
    goto label;
  }

Divide Program. You Enter 2 number and we return result
Enter 1st Number:
4
Enter 2nd Number:
k
Invalid Input

More Details about Error:System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffe r& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo in fo) at System.Convert.ToInt32(String value) at Exception_Handling.Program.Main(String[] args) in c:\Users\Prashant\Docume nts\Visual Studio 2012\Projects\advancecsharp\Exception Handling\Exception Handl ing\Program.cs:line 24Finally Block: For Continue Press Enter and for Exit press Ctrl + c __

Summary

In this chapter you have learned try catch and finally block in a brief. It is necessary to learn exception handling for all who want to be a good c# programmer. In the next chapter we will learn how to create your own exception or user defined exception.

 

Share your thought