CSharp - What is the output: exception handler?

Question

What is the output of the following code?

using System;
class Program
{
    static void Main(string[] args)
    {
        int a = 100, b = 0;
        try
        {
            int c = a / b;
            Console.WriteLine(" So, the result of a/b is :{0}", c);
        }
        catch (ArithmeticException ex)
        {
            Console.WriteLine("Encountered an exception :{0}", ex.Message);
        }
        catch (DivideByZeroException ex)
        {
            Console.WriteLine("Encountered an DivideByZeoException :{0}", ex.Message);
        }
    }
}


Click to view the answer

Compiler error.

Note

Exceptions follow the inheritance hierarchy.

We need to place catch blocks properly.

DivideByZeroException is a subclass of ArithmeticException which is a subclass of Exception.

When you deal with multiple catch blocks, you need to place more specific exception clause first.

Related Quiz