C# - Nesting of Try and Catch Blocks
Last Updated :
25 Jan, 2025
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
C#
// C# program to demonstrate nested try and catch blocks
using System;
class Geeks
{
static void Main()
{
int[] num = { 8, 17, 24, 5 };
int[] divisors = { 2, 0, 5 };
// Outer try block
try
{
for (int i = 0; i < num.Length; i++)
{
// Inner try block
try
{
Console.WriteLine($"Number: {num[i]}, Divisor: {divisors[i]}");
Console.WriteLine($"Quotient: {num[i] / divisors[i]}");
}
// Inner catch block
catch (DivideByZeroException)
{
Console.WriteLine("Inner Try Catch Block: Division by zero error.");
}
}
}
// Outer catch block
catch (IndexOutOfRangeException)
{
Console.WriteLine("Outer Try Catch Block: Index out of range error.");
}
}
}
OutputNumber: 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:
- If an exception is raised in the inner try block and is not caught by its associated catch block, the exception propagates to the outer try block.
- A try block must be followed by at least one catch or finally block. If we use a try block without a catch or finally then we will tend to a compile-time error.
- The outer block only catches exceptions that are not caught by the inner block.
- Nested try blocks enable the program to handle specific groups of errors in different ways.
Example 2: Handling Null Reference Exceptions
This example shows how exceptions generated in the inner try block are caught by its associated catch block.
C#
// C# program to demonstrate handling of null reference exception
using System;
public class Geeks
{
public string AuthorName {
get;
set;
}
}
class Program
{
static void Main()
{
Geeks o = null;
// Outer try block
try
{
// Inner try block
try
{
o.AuthorName = "Test";
}
// Inner catch block
catch (NullReferenceException)
{
Console.WriteLine("Inner Try Catch Block: Null reference error.");
}
}
// Outer catch block
catch (Exception)
{
Console.WriteLine("Outer Try Catch Block: General exception.");
}
}
}
OutputInner 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.
Similar Reads
C# Jump Statements (Break, Continue, Goto, Return and Throw) In C#, Jump statements are used to transfer control from one point to another point in the program due to some specified code while executing the program. In, this article, we will learn to different jump statements available to work in C#.Types of Jump StatementsThere are mainly five keywords in th
4 min read
How to Use Multiple Catch Clauses in C#? In C#, the main purpose of a catch block is to handle exceptions raised in the try block. A catch block is executed only when an exception occurs in the program. We can use multiple catch blocks with a single try block to handle different types of exceptions. Each catch block is designed to handle a
3 min read
Exception Handling in C# An exception is defined as an event that occurs during the execution of a program that is unexpected by the program code. The actions to be performed in case of occurrence of an exception is not known to the program. In such a case, we create an exception object and call the exception handler code.
6 min read
C# Program that Demonstrates Exception Handling For Invalid TypeCasting in UnBoxing Exception handling is used to handle the errors in the program. Or we can say that an exception is an event that occurs during the execution of a program that is unexpected by the program code. The actions to be performed in case of the occurrence of an exception are not known to the program. In thi
3 min read
C# finally Keyword finally keyword in C# is an important component of exception handling. It makes sure that specific cleanup code is always executed, whether an exception is thrown or not. This makes it ideal for releasing resources such as file handles, database connections, or network streams. The finally block is
4 min read
Nested Try Blocks in C++ In C++, a nested try block refers to the try-block nested inside another try or catch block. It is used to handle exceptions in cases where different exceptions occur in a different part of the code. Syntax of Nested Try Blocks The nested try/catch takes this syntax: try { // Code...... throw e2 try
3 min read