Monday 20 August 2018

C#: Catch block

‘catch’ block handles the exceptions that are thrown inside the try block. Each try block can have more than one catch blocks associated with it.

Syntax
    try {

    }
    catch (ExceptionType name) {

    }
     catch (ExceptionType name) {

    }

Each catch block handles the type of exception indicated by its argument.

Program.cs
using System;

class Program
{
   
    static void Main(string[] args)
    {
        try
        {
            int a = 10;
            int b = 0;
            int c = a / b;
        }
        catch (ArithmeticException e)
        {
            Console.WriteLine("Inside ArithmeticException " + e.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("Inside Exception" + e.Message);
        }

    }
}


Output
Inside ArithmeticException Attempted to divide by zero.


Program throws ArithmeticException, so the code in the first handler executed.

Some points to remember
1. While handling the exceptions, always handles the subclass exceptions first, next the super class. I.e., handle the ArithmeticException first, next Exception. Since ArithmeticExceptin is a subclass of Exception class. Otherwise compiler throws error.

Program.cs
using System;

class Program
{
   
    static void Main(string[] args)
    {
        try
        {
            int a = 10;
            int b = 0;
            int c = a / b;
        }
        catch (Exception e)
        {
            Console.WriteLine("Inside Exception" + e.Message);
        }

        catch (ArithmeticException e)
        {
            Console.WriteLine("Inside ArithmeticException " + e.Message);
        }
       
    }
}


Try to run above program, compiler throws error by saying ‘A previous catch clause catch all exceptions of this’.

2. A catch can contain try inside.

Program.cs
using System;

class Program
{
   
    static void Main(string[] args)
    {
        try
        {
            int a = 10;
            int b = 0;
            int c = a / b;
        }
        catch (ArithmeticException e)
        {
            Console.WriteLine("Inside ArithmeticException " + e.Message);

            try
            {

            }

            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
       
    }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment