Menu
Coddy logo textTech

Multiple Catch Blocks

Part of the Logic & Flow section of Coddy's C# journey — lesson 25 of 66.

Multiple catch blocks allow you to handle different types of exceptions with specific code for each exception type.

Start with a basic try block:

try
{
    int number = int.Parse("abc");
}

Add a catch block for a specific exception:

try
{
    int number = int.Parse("abc");
}
catch (FormatException ex)
{
    Console.WriteLine("Format Exception: " + ex.Message);
}

You can add multiple catch blocks to handle different exceptions:

try
{
    int number = int.Parse("abc");
    int result = a10 / number;
}
catch (FormatException ex)
{
    Console.WriteLine("Format Exception: " + ex.Message);
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Divide By Zero Exception: " + ex.Message);
}

The first matching catch block will execute. Order your catch blocks from most specific to most general exception types.

challenge icon

Challenge

Easy

Create a method named DivideNumbers that takes two string parameters:

  • numeratorStr: a string representing the numerator
  • denominatorStr: a string representing the denominator

The method should:

  1. Try to parse both strings to integers
  2. Try to divide the numerator by the denominator
  3. Return the result as an integer
  4. Handle FormatException by printing "Invalid format" and returning 0
  5. Handle DivideByZeroException by printing "Cannot divide by zero" and returning 0
  6. Handle any other exceptions with a general catch block that prints "An error occurred" and returning 0

Cheat sheet

Multiple catch blocks allow you to handle different types of exceptions with specific code for each exception type.

Basic try-catch with specific exception:

try
{
    int number = int.Parse("abc");
}
catch (FormatException ex)
{
    Console.WriteLine("Format Exception: " + ex.Message);
}

Multiple catch blocks for different exceptions:

try
{
    int number = int.Parse("abc");
    int result = 10 / number;
}
catch (FormatException ex)
{
    Console.WriteLine("Format Exception: " + ex.Message);
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Divide By Zero Exception: " + ex.Message);
}

The first matching catch block will execute. Order catch blocks from most specific to most general exception types.

Try it yourself

using System;

public class Program
{
    public static int DivideNumbers(string numeratorStr, string denominatorStr)
    {
        // Write your code here
    }
    
    public static void Main(string[] args)
    {
        string numeratorStr = Console.ReadLine();
        string denominatorStr = Console.ReadLine();
        
        int result = DivideNumbers(numeratorStr, denominatorStr);
        Console.WriteLine("Result: " + result);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow