C# program to demonstrate the use of nested try and catch blocks
Program.cs
int a = 1, b = 0;
try
{
    try
    {
        Console.WriteLine(a / b);
    }
    catch (Exception e)
    {
        Console.WriteLine("First Exception: " + e.ToString());
    }
    string s = null;
    Console.WriteLine(s.Length);

}
catch (Exception e)
{
    Console.WriteLine("Second Exception: " + e.ToString());
}
Output
kodingwindow@kw:~/csharp$ dotnet run
First Exception: System.DivideByZeroException: Attempted to divide by zero.
    at Program.<Main>$(String[] args) in /home/kodingwindow/csharp/Program.cs:line 6
 Second Exception: System.NullReferenceException: Object reference not set to an instance of an object.
    at Program.<Main>$(String[] args) in /home/kodingwindow/csharp/Program.cs:line 13 
kodingwindow@kw:~/csharp$ 
C# program to demonstrate the use of nested try and catch blocks
Program.cs
string s = null;
int n = 515, d = 0, result = 0;
try
{
    Console.WriteLine("Length: " + s.Length);
}
catch (InvalidOperationException e)
{
    Console.WriteLine("Exception caught in the first catch block");
}
catch (Exception e1)
{
    try
    {
        result = n / d;
    }
    catch (DivideByZeroException e2)
    {
        Console.WriteLine("Exception caught in the first nested catch block");
    }
    Console.WriteLine("Exception caught in the third catch block");
}
Output
kodingwindow@kw:~/csharp$ dotnet run
Exception caught in the first nested catch block
Exception caught in the third catch block
kodingwindow@kw:~/csharp$ 
Advertisement