IRONSOFTWAREHOME
开发者更新

C# 捕获多个异常(开发人员如何使用)

Jacob Mellor, Chief Technology Officer @ Team Iron
Jacob Mellor
Updated: 2026年4月21日

正确处理异常 对 C# 至关重要。 本教程向您展示如何使用带有多个 catch 子句的 try-catch 块。 我们将介绍如何捕获多种异常类型,使用异常过滤器,并确保资源通过finally得到清理。 目的是帮助您构建健壮且容错的 C# 应用程序。

通过学习捕获多种异常类型,您可以根据特定问题调整响应,从而提高程序的可靠性。 我们还将讨论如何应用条件到catch块中,通过when关键字,允许更精确的错误处理。

本指南将为您提供捕获异常的方法,并在您的编码项目中顺利处理常见和复杂错误。 我们还将探讨在异常处理中 IronPDF 的应用。

什么是异常处理?

C# 中的异常处理是一种用于处理运行时错误的方法,以防止程序突然终止,并在运行期间出现意外情况时进行管理。 异常处理的核心组件包括finally块。

Basic Structure of Try-Catch in C#

try 块包含可能引发异常的代码,而 catch 块负责在异常发生时进行管理。 catch块后执行代码,无论是否抛出了异常。 这是一个简单的结构:

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
}

捕获多个异常

在实际应用中,单个操作可能会抛出各种类型的异常。为了解决这个问题,C#允许您为单个catch块。 每个 catch 块可以指定不同的异常类型以处理所有异常。

为什么要捕获多个异常?

捕获多个异常对于详细的错误处理至关重要,其中操作依赖于发生的特定错误。 它使开发人员能够根据特定错误的上下文以适当的方式处理每个异常。

如何实现多个 Catch 块

以下是如何实现单个 catch 块以捕获多种异常类型的示例:

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);
}

在此代码中,特定的异常如catch块捕获。 任何其他类型的异常都由通用的Exception catch块捕获。

使用 When 关键字的异常过滤器

C# 还支持异常过滤器,允许您在 catch 块中指定条件。 此功能使用when关键字以便根据运行时条件提供对捕获哪些异常的更多控制。

以下是如何使用when关键字来添加异常过滤器:

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);
}

Finally 块的作用

catch块完成后执行代码。 它对于清理资源非常有用,例如关闭文件流或数据库连接,而不管是否发生异常。

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

IronPDF的介绍

IronPDF 是为 .NET 应用程序中的 C# 开发人员设计的综合库。 它帮助开发人员直接从 HTML 操作、管理和创建 PDF 文件。 它不需要外部依赖即可工作。

您可以在不使用和安装 Adobe Acrobat 的情况下执行任何 PDF 操作。 IronPDF 支持各种 PDF 功能,如编辑、合并、拆分和使用加密和数字签名对 PDF 文档进行保护。 开发人员可以在多种应用程序类型中使用 IronPDF,包括 Web 应用程序、桌面应用程序和服务。

内联链接:

IronPDF 的关键功能是将 HTML 转换为 PDF,保留了布局和样式。 它非常适合从 Web 内容生成 PDF,无论是用于报告、发票还是文档。 HTML 文件、URL 和 HTML 字符串都可以转换为 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");
    }
}

代码示例

以下是使用 IronPDF 从 HTML 创建 PDF 的简单 C# 示例,并处理多种类型异常的错误。 此示例假定您已在项目中安装了 IronPDF。 在 NuGet 控制台中运行此命令以安装 IronPDF:

PM > Install-Package IronPdf

这是代码:

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);
        }
    }
}

当我们运行此代码时,它在命令行中显示此消息。

C# 捕获多个异常(如何为开发者工作):图1

这是这段代码生成的 PDF 文件:

C# 捕获多个异常(如何为开发者工作):图2

确保在 IronPDF 配置正确的环境中进行测试,并根据应用需要修改 HTML 内容。 这将帮助您有效管理错误,提高 PDF 生成任务的可靠性。

结论

C# 捕获多个异常(如何为开发者工作):图3

在 C# 中处理多个异常是一项强大的功能,可为您的应用程序提供强大的错误处理能力。 通过使用多个finally块,您可以创建一个有弹性且稳定的应用程序,该程序能够优雅地处理不同的错误,并在各种错误条件下保持其完整性。

全面理解并实现多重异常处理确保您的应用程序能够有效处理意外情况。 IronPDF提供免费试用从$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

立即获取免费的 30 天试用版密钥

bullet_checked无需信用卡或创建账户
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
预约您的免费现场演示
Booking Badge related to IronPDF Product Demo

深受全球数百万工程师信赖

Iron Software 的客户徽标
获取您的无义务咨询
填写下面的表格或通过sales@ironsoftware.com
您的资料将始终保密。
深受全球数百万工程师信赖
Iron Software 的客户徽标
立即获取您的免费30 天试用密钥
无需信用卡或创建账户