.NET 帮助 C# 捕获多个异常(开发人员如何使用) Curtis Chau 已更新:七月 28, 2025 Download IronPDF NuGet 下载 DLL 下载 Windows 安装程序 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 正确处理异常 对 C# 至关重要。 本教程向您展示如何使用带有多个 catch 子句的 try-catch 块。 我们将介绍如何捕获多种异常类型、使用异常过滤器,并确保资源通过最终清理。 目的是帮助您构建健壮且容错的 C# 应用程序。 通过学习捕获多种异常类型,您可以根据特定问题调整响应,从而提高程序的可靠性。 我们还将涉及如何使用 when 关键字对 catch 块应用条件,以实现更精确的错误处理。 本指南将为您提供捕获异常的方法,并在您的编码项目中顺利处理常见和复杂错误。 我们还将探讨在异常处理中 IronPDF 的应用。 什么是异常处理? C# 中的异常处理是一种用于处理运行时错误的方法,以防止程序突然终止,并在运行期间出现意外情况时进行管理。 异常处理的核心组件包括 try、catch 和 finally 块。 在 C# 中 Try-Catch 的基本结构 try 块包含可能引发异常的代码,而 catch 块负责在异常发生时进行管理。 finally 块是可选的,它在 try 和 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 } 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 捕获多个异常 在现实应用程序中,单个操作可能抛出多种类型的异常。为了应对这种情况,C# 允许您为单个 try 块定义多个 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); } 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 在此代码中,特定异常如 IndexOutOfRangeException 和 DivideByZeroException 被各自的 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); } 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 Finally 块的作用 finally 块用于在 try 和任何 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."); } 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 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"); } } 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 代码示例 以下是使用 IronPDF 从 HTML 创建 PDF 的简单 C# 示例,并处理多种类型异常的错误。 此示例假定您已在项目中安装了 IronPDF。 在 NuGet 控制台中运行此命令以安装 IronPDF: 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); } } } 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 当我们运行此代码时,它在命令行中显示此消息。 这是这段代码生成的 PDF 文件: 确保在 IronPDF 配置正确的环境中进行测试,并根据应用需要修改 HTML 内容。 这将帮助您有效管理错误,提高 PDF 生成任务的可靠性。 结论 在 C# 中处理多个异常是一项强大的功能,可为您的应用程序提供强大的错误处理能力。 通过使用多个 catch 块、异常过滤器和 finally 块,您可以创建一个具有弹性和稳定性的应用程序,它能够优雅地处理不同的错误并在各种错误条件下保持完整性。 全面理解并实现多重异常处理确保您的应用程序能够有效处理意外情况。 IronPDF 提供 免费试用 ,从 $799 开始。 常见问题解答 在C#中处理异常的一些高级技术是什么? 在C#中处理异常的高级技术包括使用多个catch块来处理不同类型的异常,应用when关键字的异常过滤器,以及利用finally块来确保资源被清理。这些技术有助于构建健壮且容错的应用程序。 如何在C#应用程序中处理多个异常? 您可以通过使用多个catch块来处理C#应用程序中的多个异常。每个catch块都是专为处理特定类型的异常而设计的,允许对各种错误情景做出量身定制的响应。 什么是异常过滤器,它们如何工作? 异常过滤器是catch块中使用when关键字指定的条件。它们允许开发人员根据特定的运行时条件捕获异常,从而提供更精确的错误处理控制。 IronPDF如何帮助处理PDF生成中的异常? IronPDF可以集成到C#项目中,以帮助生成PDF,同时允许开发人员使用try-catch块来管理PDF创建过程中可能发生的错误。这种集成有助于确保应用程序内的容错操作。 在C#中使用finally块来管理资源为什么很重要? finally块对于管理资源(如文件流或数据库连接)至关重要,因为它会在try和catch块之后执行代码,无论是否抛出异常。它确保资源得到适当的释放和清理。 C#库可以在不依赖第三方应用程序的情况下生成PDF吗? 是的,像IronPDF这样的库允许在C#应用程序中直接生成PDF,而无需像Adobe Acrobat这样的第三方应用程序。这些库提供了转换、编辑和管理PDF文档的功能。 在错误处理中使用多个catch块有什么重要性? 在错误处理中使用多个catch块允许开发人员针对不同类型的异常采取独特的解决方法,从而提高错误响应的具体性和有效性,使应用程序更能应对各种错误条件。 开发人员如何提高C#项目的可靠性? 开发人员可以通过实施全面的异常处理策略来提高C#项目的可靠性,例如在处理复杂任务(如PDF生成)时,使用多个catch块、异常过滤器和finally块。 Curtis Chau 立即与工程团队聊天 技术作家 Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。 相关文章 已更新九月 4, 2025 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多 已更新九月 4, 2025 C# String Equals(开发者用法) 与强大的 PDF 库 IronPDF 结合使用,切换模式匹配允许您为文档处理构建更智能、更简洁的逻辑。 阅读更多 已更新八月 5, 2025 C# Switch 模式匹配(开发者用法) 与强大的 PDF 库 IronPDF 结合使用,切换模式匹配允许您为文档处理构建更智能、更简洁的逻辑。 阅读更多 WebClient C#(开发人员如何使用)C# Lambda表达式(开发人员...
已更新九月 4, 2025 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多