Complete C# Tutorial

Nested & Multiple Catch in C# - Handle Errors Like a Pro

🎯 Introduction

Ever tried fixing one problem only to run into another? 😅 Imagine Mia cooking her favorite dish. She burns the veggies (oops! 🔥) and then spills the sauce. Sounds chaotic, right? Cooking and coding aren’t that different—unexpected things can happen at any step!

That’s where Nested & Multiple Catch in C# swoop in like superheroes. 🦸‍♂️ They help your program catch different errors at different stages. So, no matter what goes wrong, your code can handle it smoothly. Cool, isn’t it? 😎

🧐 What is Nested & Multiple Catch in C#?

🔥 Nested Catch:

A nested catch block means you place a try-catch inside another catch block. This helps when handling an error might lead to another error! 😅

🔥 Multiple Catch:

Multiple catch blocks let you catch different types of exceptions separately. Each catch block handles a specific error. No mix-ups—just clean, targeted error handling! 🎯

 

📝 Syntax for Multiple Catch:

				
					try  
{  
    // Code that might throw exceptions  
}  
catch (ExceptionType1 ex)  
{  
    // Handle ExceptionType1  
}  
catch (ExceptionType2 ex)  
{  
    // Handle ExceptionType2  
}  
catch (Exception ex)  
{  
    // Catch-all block for other exceptions  
}
				
			

📝 Syntax for Nested Catch:

				
					try  
{  
    // Outer try block  
}  
catch (Exception ex)  
{  
    try  
    {  
        // Inner try block inside catch  
    }  
    catch (Exception innerEx)  
    {  
        // Handle inner exception  
    }  
}
				
			

🛠️ Example 1: Multiple Catch Blocks - Handle Different Errors

Scenario: Liam is building a calculator. Users might divide by zero or enter invalid numbers.

🚀 Code:

				
					using System;

public class Program
{
    public static void Main()
    {
        try
        {
            Console.Write("Enter first number: ");
            int num1 = int.Parse(Console.ReadLine());

            Console.Write("Enter second number: ");
            int num2 = int.Parse(Console.ReadLine());

            int result = num1 / num2;
            Console.WriteLine($"Result: {result}");
        }
        catch (FormatException)
        {
            Console.WriteLine("Invalid input! Please enter numeric values.");
        }
        catch (DivideByZeroException)
        {
            Console.WriteLine("Oops! Cannot divide by zero.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Unexpected error: {ex.Message}");
        }
    }
}
				
			

🖨️ Output:

				
					Enter first number: 10  
Enter second number: 0  
Oops! Cannot divide by zero.
				
			
				
					Enter first number: ten  
Invalid input! Please enter numeric values.
				
			

🔍 Explanation:

  • Entering 0 in the second number triggers DivideByZeroException.
  • Typing letters like ten triggers FormatException.
  • The last catch block covers any other unexpected errors.

This is like having different friends ready to help with different problems. 👫👬 Cool teamwork!

🛠️ Example 2: Nested Catch - Handle Errors Within Errors

Scenario:Emma’s program reads a file. If the file is missing, it tries to create one—but what if creation fails? 😱

🚀 Code:

				
					using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        try
        {
            string content = File.ReadAllText("data.txt");
            Console.WriteLine(content);
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("File not found. Trying to create one...");
            try
            {
                File.WriteAllText("data.txt", "Hello, World!");
                Console.WriteLine("File created successfully.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to create file: {ex.Message}");
            }
        }
    }
}
				
			

🖨️ Output:

				
					File not found. Trying to create one...  
File created successfully.
				
			

🔍 Explanation:

  • The outer catch handles the missing file.
  • Inside it, another try handles file creation errors.
  • If creating the file fails, the inner catch steps in.

It’s like having a backup plan for your backup plan! 🛡️🔄

🛠️ Example 3: Real-World Scenario - ATM Withdrawal

Scenario: Noah’s ATM program should handle invalid PINs, network errors, and low balances.

🚀 Code:

				
					using System;

public class InsufficientFundsException : Exception
{
    public InsufficientFundsException(string message) : base(message) { }
}

public class Program
{
    public static void Main()
    {
        try
        {
            Console.Write("Enter PIN: ");
            int pin = int.Parse(Console.ReadLine());

            if (pin != 1234)
                throw new UnauthorizedAccessException("Incorrect PIN!");

            Console.Write("Enter withdrawal amount: ");
            double amount = double.Parse(Console.ReadLine());

            double balance = 500;
            if (amount > balance)
                throw new InsufficientFundsException("Insufficient balance!");

            Console.WriteLine($"Withdrawal successful! New balance: ${balance - amount}");
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine(ex.Message);
        }
        catch (InsufficientFundsException ex)
        {
            Console.WriteLine(ex.Message);
        }
        catch (FormatException)
        {
            Console.WriteLine("Please enter valid numeric values.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Something went wrong: {ex.Message}");
        }
    }
}
				
			

🖨️ Output:

				
					Enter PIN: 4321  
Incorrect PIN!
				
			
				
					Enter PIN: 1234  
Enter withdrawal amount: 600  
Insufficient balance!
				
			

🔍 Explanation:

  • Wrong PIN? Caught!
  • Amount too high? Caught!
  • Non-numeric input? Also caught!

With multiple catch blocks, every issue is handled perfectly. 🎯

🛠️ Example 4: Nested & Multiple Catch Combo - Online Order System

Scenario:Sophia’s online shop checks payment and stock. Payment failures and out-of-stock items need different handling.

🚀 Code:

				
					using System;

public class OutOfStockException : Exception
{
    public OutOfStockException(string message) : base(message) { }
}

public class Program
{
    public static void Main()
    {
        try
        {
            Console.Write("Enter payment amount: ");
            double payment = double.Parse(Console.ReadLine());

            if (payment <= 0)
                throw new ArgumentException("Payment must be greater than zero!");

            try
            {
                int stock = 0; // No items in stock
                if (stock <= 0)
                    throw new OutOfStockException("Sorry, the item is out of stock!");
            }
            catch (OutOfStockException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        catch (ArgumentException ex)
        {
            Console.WriteLine(ex.Message);
        }
        catch (FormatException)
        {
            Console.WriteLine("Invalid payment amount. Please enter numbers.");
        }
    }
}
				
			

🖨️ Output:

				
					Enter payment amount: 100  
Sorry, the item is out of stock!
				
			
				
					Enter payment amount: -50  
Payment must be greater than zero!
				
			

🔍 Explanation:

  • Outer catch handles invalid payment.
  • Inner catch deals with stock issues.

It’s like double-checking your order before confirming! 🛍️✅

🏆 Conclusion

You’ve just leveled up your error-handling game with Nested & Multiple Catch in C#! 🚀 These tools ensure your programs catch problems at every step. No more unexpected crashes—just smooth, reliable code. 😎

Struggling at any point? Don’t worry! Mistakes are just stepping stones. Keep practicing, have fun, and you’ll get better every day. 💪🎉

 

👉 Next what?

Ready for more? In the next chapter, you’ll learn about common exception in C#. You’ll discover the errors that pop up often and how to tackle them easily. Don’t miss it—see you there! 😃🔥

Leave a Comment

Share this Doc

Nested & Multiple Catch

Or copy link