![]() |
VOOZH | about |
In C#, the nesting of the try-and-catch block is allowed. The nesting of a try block means one try block can be nested into another try block. The various programmer uses the outer try block to handle serious exceptions, whereas the inner block for handling normal exceptions.
Example 1: Handling DivideByZeroException and IndexOutOfRangeException
Number: 8, Divisor: 2 Quotient: 4 Number: 17, Divisor: 0 Inner Try Catch Block: Division by zero error. Number: 24, Divisor: 5 Quotient: 4 Outer Try Catch Block: Index out of range error.
Explanation: In this example, the inner try block handles division operations using the "num" and "divisors" arrays. If a number is divided by zero, the DivideByZeroException is caught by the inner catch block, allowing the program to continue. If an index goes out of range while accessing the arrays, the IndexOutOfRangeException is caught by the outer catch block, preventing the program from crashing.
Syntax:
// Outer try block
try
{ // Inner try block
try
{ // Code that may throw exceptions }
// Inner catch block
catch (ExceptionType)
{ // Handle specific exception }
}
// Outer catch block
catch (ExceptionType)
{ // Handle propagated exception }
Key Points:
Example 2: Handling Null Reference Exceptions
This example shows how exceptions generated in the inner try block are caught by its associated catch block.
Inner Try Catch Block: Null reference error.
Explanation: In the above example, a NullReferenceException is generated in the inner try block when trying to access the AuthorName property of a null object "o". This exception is caught by the inner catch block, which handles the null reference error. If any other exception occurs, it is caught by the outer catch block, which handles general exceptions.