Monday, 20 August 2018

C#: try block

Syntax
try {
   //code
}
catch and finally blocks . . .

The first step to handle the exception is enclose the error prone code in the try block. A try block must have at least one catch or finally block. Otherwise compiler throws an error.

try nested inside a try
You can enclose a try block inside other try block.

Program.cs
using System;

class Program
{
   
    static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("I am enclosing another try inside me");
            try
            {
                int a = 10;
                int b = 0;
                int c = a / b;
            }
            catch (IndexOutOfRangeException e)
            {
                Console.WriteLine("inside try block " + e.Message);
            }
        }

        catch (Exception e)
        {
            Console.WriteLine("Outside try block " + e.Message);
        }

    }
}

Output
I am enclosing another try inside me
Outside try block Attempted to divide by zero.

As you observe the program, try has try nested in it. “a / b” is called in nested try block, which has catch block associated with it. But the catch block for the nested try block handles IndexOutOfRangeException only. So while executing, the catch correspond to the outer block is executed.






Previous                                                 Next                                                 Home

No comments:

Post a Comment