Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
How to Create Threads in C#?
Next article icon

How to Use Multiple Catch Clauses in C#?

Last Updated : 25 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 specific type of exception.

Note: C# does not allow multiple catch blocks for the same exception type, because it will cause a compile-time error. The catch blocks are evaluated in the order they appear. If an exception matches the first catch block, the remaining catch blocks are ignored.

Syntax of try-catch with Multiple Catch Clauses:

try

{ // Code that may throw an exception }

catch (ExceptionType1 ex)

{ // Handle ExceptionType1 }

catch (ExceptionType2 ex)

{ // Handle ExceptionType2 }

// Add more catch blocks as needed

finally

{ // Code that executes regardless of exceptions (optional) }

Example 1: Handling DivideByZeroException and IndexOutOfRangeException

In this example, the try block generates two types of exceptions:

  • DivideByZeroException: When trying to divide a number by zero.
  • IndexOutOfRangeException: When accessing an array with an invalid index.

Each exception is handled by a specific catch block.

C#
// C# program to illustrate multiple catch blocks using System;  class Geeks {     static void Main()     {         // Arrays for demonstration         int[] num = { 8, 17,5 };         int[] divisors = { 2, 0, 4 };          // Iterate through numbers and divisors         for (int i = 0; i < num.Length; i++)         {             try             {                 // Display current number and divisor                 Console.WriteLine($"Number: {num[i]}");                 Console.WriteLine($"Divisor: {divisors[i]}");                  // Perform division                 Console.WriteLine($"Quotient: {num[i] / divisors[i]}");             }             catch (DivideByZeroException)             {                 // Handle division by zero                 Console.WriteLine("Error: Division by zero is not allowed.");             }             catch (IndexOutOfRangeException)             {                 // Handle invalid array index                 Console.WriteLine("Error: Index is out of range.");             }             finally             {                 // Execute cleanup code (if needed)                 Console.WriteLine("Operation completed.\n");             }         }     } } 

Output
Number: 8 Divisor: 2 Quotient: 4 Operation completed.  Number: 17 Divisor: 0 Error: Division by zero is not allowed. Operation completed.  Number: 5 Divisor: 4 Quotient: 1 Operation completed.


Example 2: Handling Multiple Exception Types in Parsing

This example demonstrates using multiple catch blocks to handle exceptions such as FormatException (invalid input format) and OverflowException (data out of range).

C#
// C# program to demonstrate multiple catch clauses using System;  class Geeks {     static void Main()     {         try         {             // Trying to parse invalid input             byte data = byte.Parse("a");             Console.WriteLine($"Parsed Data: {data}");         }         catch (FormatException)         {             // Handle invalid input format             Console.WriteLine("Error: The entered value is not a valid number.");         }         catch (OverflowException)         {             // Handle data out of range for a byte             Console.WriteLine               ("Error: The entered value is outside the valid range for a byte.");         }         catch (Exception ex)         {             // General exception handling (fallback)             Console.WriteLine($"Unexpected error: {ex.Message}");         }         finally         {             // Execute code regardless of exceptions             Console.WriteLine("Operation completed.");         }     } } 

Output
Error: The entered value is not a valid number. Operation completed. 

Important Points:

  • The catch blocks are evaluated in the order they appear. Ensure more specific exceptions (e.g., DivideByZeroException) appear before more general ones (e.g., Exception).
  • Use a finally block for cleanup operations like closing resources, which should run regardless of whether an exception is raised.
  • Always use a general catch (Exception ex) block at the end to handle any unexpected exceptions.


Next Article
How to Create Threads in C#?
author
ankita_saini
Improve
Article Tags :
  • C#
  • CSharp-Exception-Handling

Similar Reads

  • How to Create Threads in C#?
    Multithreading enables concurrent task execution in C#. It improves performance and responsiveness. We can create threads using the System.Threading namespace. With the help of Threads, we can achieve multitasking and can define their behavior using different methods provided by the Thread Class. Ex
    6 min read
  • How to compare two ValueTuple in C#?
    To compare two instances of ValueTuple you can use CompareTo method which is provided by ValueTuple structure. ValueTuple.CompareTo(ValueTuple) Method is used to compare the current instance of ValueTuple with another ValueTuple instance. It always returns zero if they are equal to each other. Synta
    2 min read
  • How to Compare Strings in C#?
    A string is a collection of characters and is used to store plain text. Unlike C or C++, a string in C# is not terminated with a null character. The maximum size of a string object depends on the internal architecture of the system. A variable declared followed by "string" is actually an object of s
    13 min read
  • Null-Coalescing Operator in C#
    In C#, ?? operator is known as Null-coalescing operator. It will return the value of its left-hand operand if it is not null. If it is null, then it will evaluate the right-hand operand and returns its result. Or if the left-hand operand evaluates to non-null, then it does not evaluate its right-han
    4 min read
  • List FindLastIndex() Method in C# | Set -1
    This method is used to search for an element which matches the conditions defined by a specified predicate and returns the zero-based index of the last occurrence within the List<T> or a portion of it. There are 3 methods in the overload list of this method: FindLastIndex(Predicate<T>) M
    3 min read
  • List FindLastIndex() Method in C# | Set -2
    This method is used to search for an element which matches the conditions defined by a specified predicate and returns the zero-based index of the last occurrence within the List<T> or a portion of it. There are 3 methods in the overload list of this method: FindLastIndex(Predicate<T>) M
    5 min read
  • How to Terminate a Thread in C#?
    In C#, threads are used to achieve tasks concurrently, a fundamental feature in multithreading and parallel programming. However, there are scenarios where we need to terminate a thread. There are different ways to terminate a thread and in this article, we will discuss those ways with their code im
    6 min read
  • C# | How to use strings in switch statement
    The switch statement is a multiway branch statement. It provides an easy way to forward execution to different parts of code based on the value of the expression. String is the only non-integer type which can be used in switch statement. Important points: Switching on strings can be more costly in t
    2 min read
  • How to Schedule a Thread for Execution in C#?
    In C#, we can schedule a thread for execution using the Thread class. The Thread.Start() method is responsible for scheduling a thread, allowing it to run when system resources are available. This method can be overloaded to pass parameters to the thread. Also, the Thread.Sleep() method can be used
    3 min read
  • Console.SetError() Method in C#
    The Console.SetError(TextWriter) Method sets the Error property of the specified StreamWriter i.e., it redirects the standard error stream to a file. As the console is set with this StreamWriter object, the WriteLine() method can be called to write the error into the file. Syntax: public static void
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences