.NET幫助 C# Catch Multiple Exceptions(對於開發者的運行原理) Curtis Chau 更新日期:7月 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# 中是必不可少的。 本教程示範如何使用帶有多個捕捉子句的 try-catch 區塊。 我們將介紹如何捕捉多種例外類型、使用例外過濾器以及確保資源最終被清理。 目的是幫助您構建穩健且容錯的 C# 應用程式。 通過學習捕捉多種例外,您可以針對特定問題量身定制應對措施,提高程式的可靠性。 我們還將介紹如何使用 when 關鍵字將條件應用於捕捉區塊,以實現更精確的錯誤處理。 本指南將為您提供方法,以便輕鬆地在編碼專案中捕捉例外,並處理常見和複雜的錯誤。 我們還將在例外處理的背景下探討 IronPDF。 什麼是例外處理? C# 中的例外處理是一種用於處理運行時錯誤的方法,以防止程式突然終止,並在程式執行過程中發生意外情況時進行管理。 例外處理的核心組件包括 try、catch 和 finally 區塊。 Try-Catch 的基本結構在 C# 中 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 區塊可以指定一種不同的例外類型來處理所有例外。 為什麼要捕捉多個例外? 捕捉多個例外對於詳細的錯誤處理非常重要,因為行動取決於發生的具體錯誤。 這使開發人員能夠以適合於特定錯誤情境的方式來處理每個例外。 如何實現多個捕捉區塊 以下是一個實現單個捕捉區塊來捕捉多種例外類型的範例: 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 捕捉區塊捕捉。 使用 Exception Filters 與 When 關鍵字 C# 還支持例外過濾器,允許您在捕獲區塊內指定條件。 此功能使用 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 是一個專為 C# 開發人員設計的全面的庫,適用於 .NET 應用程式。 它幫助開發人員操作、管理並直接從 HTML 創建 PDF 文件。 它不需依賴外部依賴來工作。 您可以執行任何 PDF 操作,而不必使用和安裝 Adobe Acrobat。 IronPDF 支援各種 PDF 功能,例如編輯、合併、拆分以及使用加密和數位簽名來保護 PDF 文檔。 開發人員可以在多種應用程式類型中利用 IronPDF,包括網頁應用程式、桌面應用程式和服務。 相互連接: IronPDF 的關鍵功能是將HTML 轉換為 PDF,能保留佈局和樣式。 非常適合從網頁內容生成 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#應用程式中處理多個異常? 您可以在C#應用程式中使用多個catch塊來處理多個異常。每個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#項目的可靠性,例如使用多個catch塊、異常過濾器和finally塊,尤其在處理像PDF生成功能這樣的複雜任務時。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 WebClient C#(對於開發者的運行原理)C# Lambda Expressions(對於開...