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
EasyCreate a method named DivideNumbers that takes two string parameters:
numeratorStr: a string representing the numeratordenominatorStr: a string representing the denominator
The method should:
- Try to parse both strings to integers
- Try to divide the numerator by the denominator
- Return the result as an integer
- Handle FormatException by printing "Invalid format" and returning 0
- Handle DivideByZeroException by printing "Cannot divide by zero" and returning 0
- 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);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety