跳過到頁腳內容
.NET幫助

C# Catch Multiple Exceptions(對於開發者的運行原理)

正確地處理例外 在C#中是至關重要的。 本教程向您展示如何使用帶有多個 catch 子句的 try-catch 區塊。 我們將介紹如何捕獲多種例外類型、使用例外過濾器並確保資源在最終性中被清理乾淨。 目的是幫助您構建穩健且容錯的C#應用程式。

通過學會捕獲多種類型的例外,您可以針對特定問題量身定制回應,從而提高程式的可靠性。 我們還將涉及如何使用 when 關鍵字為 catch 區塊應用條件,允許更精確的錯誤處理。

本指南將向您提供捕獲例外的方法,並在您的編碼專案中順利處理常見和複雜的錯誤。 我們還將在例外處理的背景下探討 IronPDF

什麼是例外處理?

C#中的例外處理是一種用於處理運行時錯誤的工具,防止程式的突然終止,並在程式執行期間發生意外情況時進行管理。 例外處理的核心組成包括 catchfinally 區塊。

Basic Structure of Try-Catch in C

try 區塊包括可能觸發例外的程式碼,而 catch 區塊負責管理如果發生的例外。 finally 區塊是可選的,並在 trycatch 區塊之後執行程式碼,無論是否拋出了例外。 這是簡單的結構:

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

在此程式碼中,特定的例外如 IndexOutOfRangeExceptionDivideByZeroException 被它們各自的 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,保留了佈局和樣式。 它非常適合從網頁內容生成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

當我們運行此程式碼時,此訊息會在命令列中顯示。

C# 捕獲多個例外(開發者如何運作):圖1

這是由此程式碼生成的PDF文件:

C# 捕獲多個例外(開發者如何運作):圖2

確保在正確配置IronPDF的環境中進行測試,並根據應用程式需求修改HTML內容。 這將幫助您有效管理錯誤,提高PDF生成任務的可靠性。

結論

C# 捕獲多個例外(開發者如何運作):圖3

在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塊對於管理資源(如文件流或數據庫連接)至關重要,因為無論是否拋出異常,它都會在trycatch塊後執行代碼。它確保資源被正確釋放和清理。

是否可以在不依賴於第三方應用程序的情況下使用C#庫生成PDF?

是的,像IronPDF這樣的庫允許在C#應用程式中直接生成PDF,而無需依賴於像Adobe Acrobat這樣的第三方應用程式。這些庫提供轉換、編輯和管理PDF文檔的功能。

在錯誤處理中使用多個catch塊有何意義?

在錯誤處理中使用多個catch塊允許開發人員獨特地處理不同類型的異常,從而提高錯誤回應的針對性和有效性,使應用程式對各種錯誤條件更具抗壓性。

開發人員如何提高C#項目的可靠性?

開發人員可以通過實施全面的異常處理策略來增強其C#項目的可靠性,例如使用多個catch塊、異常過濾器和finally塊,尤其在處理像PDF生成功能這樣的複雜任務時。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我