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# Tutorial C# (pronounced "C-sharp") is a modern, versatile, object-oriented programming language developed by Microsoft in 2000 that runs on the .NET Framework. Whether you're creating Windows applications, diving into Unity game development, or working on enterprise solutions, C# is one of the top choices fo
4 min read
Introduction to .NET Framework The .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The .NET framework is primarily used on Windows, while .NET Core (which evolved into
6 min read
C# Interview Questions and Answers C# is the most popular general-purpose programming language and was developed by Microsoft in 2000, renowned for its robustness, flexibility, and extensive application range. It is simple and has an object-oriented programming concept that can be used for creating different types of applications.Her
15+ min read
C# Dictionary Dictionary in C# is a generic collection that stores key-value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of a Dictionary is, that it is a generic type. A dictionary is defined under System.Collections.Generic namespace. It is dynamic in nature mean
5 min read
C# List Class In C#, the List<T> class represents the list of objects that can be accessed by index. It comes under the System.Collections.Generic namespace. List class can be used to create a collection of different types like integers, strings, etc. List<T> class also provides the methods to search,
7 min read
C# Delegates A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. It provides a way which tells which method is to be called when an event is triggered. For example, if you click on a Button on a form (Windows Form application),
6 min read
ASP.NET Interview Questions and Answer ASP.NET is a popular framework by Microsoft for building fast and scalable web applications. It allows developers to create dynamic websites, services, and apps, using server-side code and offering a user-friendly experience. Trusted by companies like Microsoft, Dell, and Accenture, ASP.NET is used
15+ min read
C# .NET Framework (Basic Architecture and Component Stack) C# (C-Sharp) is a modern, object-oriented programming language developed by Microsoft in 2000. It is a part of the .NET ecosystem and is widely used for building desktop, web, mobile, cloud, and enterprise applications. This is originally tied to the .NET Framework, C# has evolved to be the primary
6 min read
C# Data Types Data types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C# each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given pr
7 min read
C# Arrays An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array spe
8 min read