IRONSOFTWAREHOME
.NET HELP

C# Catch Multiple Exceptions (How It Works For Developers)

Jacob Mellor, Chief Technology Officer @ Team Iron
Jacob Mellor
Updated: August 1, 2026

Handling exceptions properly is essential in C#. This tutorial shows you how to use a try-catch block with multiple catch clauses. We'll cover how to catch multiple exception types, use exception filters, and ensure resources are cleaned up with finally. The aim is to help you build robust and error-tolerant C# applications.

By learning to catch multiple types of exceptions, you can tailor responses to specific problems, improving your program's reliability. We'll also touch on how to apply conditions to catch blocks with the when keyword, allowing for more precise error handling.

This guide will give you the methods to catch exceptions and handle both common and complex errors smoothly in your coding projects. We'll also explore IronPDF in the context of exception handling.

What is Exception Handling?

Exception handling in C# is a method used to handle runtime errors, prevent abrupt termination of a program, and manage unexpected situations when they occur during the execution of a program. The core components of exception handling include the try, catch, and finally blocks.

Basic Structure of Try-Catch in C#

The try block includes code that could potentially trigger an exception, whereas the catch block is responsible for managing the exception if it arises. The finally block is optional and executes code after the try-and-catch blocks, regardless of whether an exception was thrown or not. Here's a simple structure:

try
{
    // Code that may throw an exception
}
catch (Exception e)
{
    // Code to handle the exception
}
finally
{
    // Code that executes after try and catch, regardless of an exception
}

Catching Multiple Exceptions

In real-world applications, a single operation might throw exceptions of various types. To address this, C# allows you to define multiple catch blocks for a single try block. Each catch block can specify a different exception type to handle all the exceptions.

Why Catch Multiple Exceptions?

Catching multiple exceptions is essential for detailed error handling, where actions depend on the specific error that occurred. It enables developers to handle each exception in a way that is appropriate for the context of that particular error.

How to Implement Multiple Catch Blocks

Here's an example of how to implement a single catch block to catch multiple exception types:

try
{
    // Code that may throw multiple types of exceptions
    int[] numbers = { 1, 2, 3 };
    Console.WriteLine(numbers[5]); // This will throw an IndexOutOfRangeException
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine("An index was out of range: " + ex.Message);
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Can't divide by Zero: " + ex.Message);
}
catch (Exception ex)
{
    Console.WriteLine("Error: " + ex.Message);
}

In this code, specific exceptions like IndexOutOfRangeException and DivideByZeroException are caught by their respective catch blocks. Any other types of exceptions are caught by the generic Exception catch block.

Using Exception Filters with the When Keyword

C# also supports exception filters that allow you to specify a condition within the catch block. This feature uses the when keyword to provide more control over which exceptions to catch based on the condition evaluated at runtime.

Here is how you can use the when keyword to add exception filters:

try
{
    // Code that may throw an exception
    throw new InvalidOperationException("Invalid operation occurred", new Exception("Inner exception"));
}
catch (Exception ex) when (ex.InnerException != null)
{
    Console.WriteLine("Exception with inner exception caught: " + ex.Message);
}
catch (Exception ex)
{
    Console.WriteLine("Exception caught: " + ex.Message);
}

The Role of the Finally Block

The finally block is used to execute code after the try and any catch blocks are complete. It is useful for cleaning up resources, like closing file streams or database connections, regardless of whether an exception occurred.

try
{
    // Code that might throw an exception
}
catch (Exception e)
{
    // Handle the exception
}
finally
{
    // Cleanup code, executed after try/catch
    Console.WriteLine("Cleanup code runs here.");
}

Introduction of IronPDF

IronPDF is a comprehensive library designed for C# developers working within the .NET applications. It helps developers to manipulate, manage, and create PDF files directly from HTML. It does not require an external dependency to work.

You can do any PDF operation without using and installing Adobe Acrobat. IronPDF supports various PDF functionalities such as editing, merging, splitting, and securing PDF documents with encryption and digital signatures. Developers can utilize IronPDF in multiple application types, including web applications, desktop applications, and services.

Interlink:

The key feature of IronPDF is converting HTML to PDF, which retains both layout and style. It's perfect for producing PDFs from web content, whether it's for reports, invoices, or documentation. HTML files, URLs, and HTML strings can all be converted to PDF files.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}

Code Example

Here's a simple C# example using IronPDF to create a PDF from HTML, with error handling for multiple types of exceptions. This example assumes you have IronPDF installed in your project. Run this command in the NuGet console to install IronPDF:

PM > Install-Package IronPdf

Here is the code:

using IronPdf;
using System;

class Program
{
    static void Main(string[] args)
    {
        // Set your IronPDF license key, if applicable.
        License.LicenseKey = "License-Key";
        var renderer = new ChromePdfRenderer();
        
        try
        {
            // Convert HTML to PDF
            var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
            pdf.SaveAs("Exceptions.pdf");
            Console.WriteLine("PDF successfully created.");
        }
        catch (IronPdf.Exceptions.IronPdfProductException ex)
        {
            // Handle PDF generation errors
            Console.WriteLine("Failed to generate PDF: " + ex.Message);
        }
        catch (System.IO.IOException ex)
        {
            // Handle IO errors (e.g., disk I/O errors)
            Console.WriteLine("IO Exception: " + ex.Message);
        }
        catch (Exception ex)
        {
            // Handle other errors
            Console.WriteLine("Error: " + ex.Message);
        }
    }
}

When we run this code, it shows up this message in the command line.

C# Catch Multiple Exceptions (How It Works For Developers): Figure 1

And it is the PDF file generated by this code:

C# Catch Multiple Exceptions (How It Works For Developers): Figure 2

Make sure to test this in an environment where IronPDF is properly configured, and modify the HTML content as needed for your application. This will help you manage errors efficiently, improving the reliability of your PDF generation tasks.

Conclusion

C# Catch Multiple Exceptions (How It Works For Developers): Figure 3

Handling multiple exceptions in C# is a powerful feature that provides robust error-handling capabilities in your applications. By using multiple catch blocks, exception filters, and the finally block, you can create a resilient and stable application that handles different errors gracefully and maintains its integrity under various error conditions.

This comprehensive understanding and implementation of multiple exception handling ensure that your applications are well-prepared to deal with unexpected situations effectively. IronPDF offers a free trial starts from $999.

Jacob Mellor, Chief Technology Officer @ Team Iron
Chief Technology Officer

Jacob Mellor is Chief Technology Officer at Iron Software and a visionary engineer pioneering C# PDF technology. As the original developer behind Iron Software's core codebase, he has shaped the company's product architecture since its inception, transforming it alongside CEO Cameron Rimington into a 50+ person company serving NASA, Tesla, and global government agencies.

...
Read More

Related Articles

Key in blue circle

Get your free 30-day Trial Key instantly.

bullet_checkedNo credit card or account creation required
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
Book your free Live Demo
Booking Badge related to IronPDF Product Demo

Trusted by Millions of Engineers Worldwide

Iron Software's customer logos
Get Your No-Obligation Consult
Complete the form below or email sales@ironsoftware.com
Your details will always be kept confidential.
Trusted by Millions of Engineers Worldwide
Iron Software's customer logos
Get your free 30-day Trial Key instantly.
No credit card or account creation required