Skip to footer content
.NET HELP

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

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 finality. 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
}
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
}
Try
	' Code that may throw an exception
Catch e As Exception
	' Code to handle the exception
Finally
	' Code that executes after try and catch, regardless of an exception
End Try
$vbLabelText   $csharpLabel

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);
}
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);
}
Try
	' Code that may throw multiple types of exceptions
	Dim numbers() As Integer = { 1, 2, 3 }
	Console.WriteLine(numbers(5)) ' This will throw an IndexOutOfRangeException
Catch ex As IndexOutOfRangeException
	Console.WriteLine("An index was out of range: " & ex.Message)
Catch ex As DivideByZeroException
	Console.WriteLine("Can't divide by Zero: " & ex.Message)
Catch ex As Exception
	Console.WriteLine("Error: " & ex.Message)
End Try
$vbLabelText   $csharpLabel

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);
}
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);
}
Try
	' Code that may throw an exception
	Throw New InvalidOperationException("Invalid operation occurred", New Exception("Inner exception"))
Catch ex As Exception When ex.InnerException IsNot Nothing
	Console.WriteLine("Exception with inner exception caught: " & ex.Message)
Catch ex As Exception
	Console.WriteLine("Exception caught: " & ex.Message)
End Try
$vbLabelText   $csharpLabel

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.");
}
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.");
}
Try
	' Code that might throw an exception
Catch e As Exception
	' Handle the exception
Finally
	' Cleanup code, executed after try/catch
	Console.WriteLine("Cleanup code runs here.")
End Try
$vbLabelText   $csharpLabel

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 the 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");
    }
}
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");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

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

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

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

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:

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);
        }
    }
}
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);
        }
    }
}
Imports IronPdf
Imports System

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Set your IronPDF license key, if applicable.
		License.LicenseKey = "License-Key"
		Dim renderer = New ChromePdfRenderer()

		Try
			' Convert HTML to PDF
			Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>")
			pdf.SaveAs("Exceptions.pdf")
			Console.WriteLine("PDF successfully created.")
		Catch ex As IronPdf.Exceptions.IronPdfProductException
			' Handle PDF generation errors
			Console.WriteLine("Failed to generate PDF: " & ex.Message)
		Catch ex As System.IO.IOException
			' Handle IO errors (e.g., disk I/O errors)
			Console.WriteLine("IO Exception: " & ex.Message)
		Catch ex As Exception
			' Handle other errors
			Console.WriteLine("Error: " & ex.Message)
		End Try
	End Sub
End Class
$vbLabelText   $csharpLabel

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 $749.

Frequently Asked Questions

What are some advanced techniques for handling exceptions in C#?

Advanced techniques for handling exceptions in C# include using multiple catch blocks to handle different exception types, applying exception filters with the when keyword, and utilizing the finally block to ensure resources are cleaned up. These techniques help build robust and error-tolerant applications.

How can you handle multiple exceptions in a C# application?

You can handle multiple exceptions in a C# application by using multiple catch blocks. Each catch block is designed to handle a specific type of exception, allowing for tailored responses to various error scenarios.

What are exception filters and how do they work?

Exception filters are conditions specified in a catch block using the when keyword. They allow developers to catch exceptions based on specific runtime conditions, providing more precise control over error handling.

How can IronPDF assist with handling exceptions in PDF generation?

IronPDF can be integrated into C# projects to aid in PDF generation while allowing developers to use try-catch blocks to manage errors that may occur during the PDF creation process. This integration helps ensure error-tolerant operations within applications.

Why is it important to manage resources with a finally block in C#?

The finally block is crucial for managing resources such as file streams or database connections, as it executes code after try and catch blocks regardless of whether an exception is thrown. It ensures that resources are properly released and cleaned up.

Can C# libraries be used to generate PDFs without relying on third-party applications?

Yes, libraries like IronPDF allow for PDF generation directly within C# applications without the need for third-party applications like Adobe Acrobat. These libraries provide functionality for converting, editing, and managing PDF documents.

What is the significance of using multiple catch blocks in error handling?

Using multiple catch blocks in error handling allows developers to address different types of exceptions uniquely, improving the specificity and effectiveness of error responses and making the application more resilient to various error conditions.

How can developers improve the reliability of their C# projects?

Developers can enhance the reliability of their C# projects by implementing comprehensive exception handling strategies, such as using multiple catch blocks, exception filters, and finally blocks, particularly when dealing with complex tasks like PDF generation.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of ...Read More