C# | Nesting of try and catch blocks
Last Updated :
01 Aug, 2019
In C#, the nesting of the try & catch block is allowed. The nesting of try block means one try block can be nested into another try block. The various programmer uses the outer try block to handling serious exceptions, whereas the inner block for handling normal exceptions.
Note:
- If an exception raises in the inner try block that is not caught by the catch block associated with the try block, then the exception is promoted to the outer try block. Generally, nested try blocks are used to permit different groups of the error to be handled in different ways.
- It is a necessary condition that a try block must be followed by a catch or finally blocks because if you use a try block without a catch or finally then you will tend to a compile-time error.
Syntax:
// outer try block
try
{
// inner try block
try
{
// code...
}
// inner catch block
catch
{
// code...
}
}
// outer catch block
catch
{
// code...
}
Below given are some examples to understand the implementation in a better way:
Example 1: In this program, DivideByZeroException is generated within the inner try block that is caught by a catch block associated with the inner try block and continue the flow of the program. When IndexOutOfRangeException generates within the inner try block which is not caught by the inner catch block then inner try block transfer this exception to the outer try block. After that, the catch block associated with the outer try block caught the exception which causes the program to terminate. Here for 17/0 and 24/0 inner try-catch block is executing but for number 25 outer try-catch block is executing.
using System;
class GFG {
static void Main()
{
int [] number = {8, 17, 24, 5, 25};
int [] divisor = {2, 0, 0, 5};
try {
for ( int j = 0; j < number.Length; j++) {
try {
Console.WriteLine( "Number: " + number[j] +
"\nDivisor: " + divisor[j] +
"\nQuotient: " + number[j] / divisor[j]);
}
catch (DivideByZeroException) {
Console.WriteLine( "Inner Try Catch Block" );
}
}
}
catch (IndexOutOfRangeException) {
Console.WriteLine( "Outer Try Catch Block" );
}
}
}
|
Output:
Number: 8
Divisor: 2
Quotient: 4
Inner Try Catch Block
Inner Try Catch Block
Number: 5
Divisor: 5
Quotient: 1
Outer Try Catch Block
Example 2: In the below example, an exception is generated within the inner try block that is caught by the catch block associated with the inner try block.
using System;
public class Geeks {
public string Author_name
{
get ;
set ;
}
}
public class GFG {
public static void Main()
{
Geeks str1 = null ;
try {
try {
str1.Author_name = "" ;
}
catch {
Console.WriteLine( "Inner try catch block" );
}
}
catch {
Console.WriteLine( "Outer try catch block" );
}
}
}
|
Output:
Inner try catch block
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...