Nested try catch program in C Sharp

Try block with in the try block is called Nested try block.

There are some scenarios where exception arises in one part of the application that causes the entire block as an another error.
To handle such scenarios we use Nested try block.

For Example you are calculating the division of 2 numbers and also displaying student names in the console with in the code block.

Suppose if zero divide exception occured while performing division operation, because of this exception entire block causes for the error.

We can handle this by using nested try blocks. one try block for division operation and another try block for displaying student names.


If exception occurs in one try block, it cannot cause the error for the whole program.
We can handle this exceptions with catch and finally blocks.

C# Program to handle multiple scenarios using nested try block.

C# Code

 /*
  * In this program we can see that try 
  * block inside try block is used in order 
  * to get multiple exceptions through multiple 
  * catch block
  */
    public class Exceptions
    {

        public static void Main(String[] args) 
        {
 
		try {
 
			try {
				  int a = 10;
				  int b = 0;
 
				//it will throw an exception because value 0 is place
                    //in denominator of the arithmetical calculation.
 
				   Console.WriteLine("Div: " + (a / b));
 
				} 
            catch (ArithmeticException ea) 
            {
				Console.WriteLine(ea);
			}

            try {
					int[] s = { 10, 20 };
 
					/*
					 * I'm trying to display the value of an element which
					 * doesn't exist. The code should throw an exception
					 */
 
					Console.WriteLine("s" + s[3]);
 
				} 
            catch (IndexOutOfRangeException ae) 
            {
					Console.WriteLine(ae);
            }
		} 
        catch (Exception e) 
        {
            Console.WriteLine(e);
		}
	}
    }

Output

System.DivideByZeroException: Attempted to divide by zero.
at Nested_Try_Catch.Exceptions.Main(String[] args) in e:\PRACTICECODEFORALLDO
TNETBASICS\MASTERPROJECT\Nested Try Catch\Nested Try Catch\Program.cs:line 30
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Nested_Try_Catch.Exceptions.Main(String[] args) in e:\PRACTICECODEFORALLDO
TNETBASICS\MASTERPROJECT\Nested Try Catch\Nested Try Catch\Program.cs:line 46

Related Posts