푸터 콘텐츠로 바로가기
.NET 도움말

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
}
$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);
}
$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);
}
$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.");
}
$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");
    }
}
$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);
        }
    }
}
$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 $799.

자주 묻는 질문

C#에서 예외를 처리하는 고급 기술에는 어떤 것이 있나요?

C#에서 예외를 처리하는 고급 기술에는 여러 catch 블록을 사용하여 다양한 예외 유형을 처리하고, when 키워드로 예외 필터를 적용하고, finally 블록을 활용하여 리소스가 정리되도록 하는 방법이 포함됩니다. 이러한 기술은 견고하고 오류에 강한 애플리케이션을 구축하는 데 도움이 됩니다.

C# 애플리케이션에서 여러 예외를 어떻게 처리할 수 있나요?

여러 개의 catch 블록을 사용하여 C# 애플리케이션에서 여러 예외를 처리할 수 있습니다. 각 catch 블록은 특정 유형의 예외를 처리하도록 설계되어 다양한 오류 시나리오에 맞춤형으로 대응할 수 있습니다.

예외 필터란 무엇이며 어떻게 작동하나요?

예외 필터는 when 키워드를 사용하여 catch 블록에 지정된 조건입니다. 이를 통해 개발자는 특정 런타임 조건에 따라 예외를 포착하여 오류 처리를 보다 정밀하게 제어할 수 있습니다.

IronPDF는 PDF 생성 시 예외 처리를 어떻게 지원하나요?

IronPDF를 C# 프로젝트에 통합하여 PDF 생성을 지원하는 동시에 개발자가 try-catch 블록을 사용하여 PDF 생성 프로세스 중에 발생할 수 있는 오류를 관리할 수 있도록 할 수 있습니다. 이러한 통합을 통해 애플리케이션 내에서 오류를 허용하는 작업을 보장할 수 있습니다.

C#에서 최종 블록으로 리소스를 관리하는 것이 중요한 이유는 무엇인가요?

finally 블록은 예외 발생 여부에 관계없이 trycatch 블록 다음에 코드를 실행하므로 파일 스트림이나 데이터베이스 연결과 같은 리소스를 관리하는 데 매우 중요합니다. 리소스가 적절하게 해제되고 정리되도록 보장합니다.

타사 애플리케이션에 의존하지 않고 C# 라이브러리를 사용하여 PDF를 생성할 수 있나요?

예, IronPDF와 같은 라이브러리를 사용하면 Adobe Acrobat과 같은 타사 애플리케이션 없이도 C# 애플리케이션 내에서 직접 PDF를 생성할 수 있습니다. 이러한 라이브러리는 PDF 문서를 변환, 편집 및 관리하기 위한 기능을 제공합니다.

오류 처리에서 여러 개의 캐치 블록을 사용하는 것의 의미는 무엇인가요?

개발자는 오류 처리에서 여러 catch 블록을 사용하면 다양한 유형의 예외를 고유하게 처리하여 오류 응답의 구체성과 효율성을 개선하고 애플리케이션을 다양한 오류 조건에 더 탄력적으로 만들 수 있습니다.

개발자는 C# 프로젝트의 안정성을 어떻게 향상시킬 수 있을까요?

개발자는 특히 PDF 생성과 같은 복잡한 작업을 처리할 때 여러 캐치 블록, 예외 필터, 마지막 블록을 사용하는 등 포괄적인 예외 처리 전략을 구현하여 C# 프로젝트의 안정성을 높일 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.