跳過到頁腳內容
.NET HELP

C# Catch Multiple Exceptions (How It Works For Developers)

正確處理異常在 C# 中是非常重要的。 本教學教導您如何使用具有多重 catch 子句的 try-catch 區塊。 我們將介紹如何捕捉多種異常類型,使用異常過濾器,並確保資源得到最後清理。 目的是幫助您建立穩健且容錯的 C# 應用程式。

透過學習捕捉多種類型的異常,您可以針對特定問題量身訂做回應,以提高程式的可靠性。 我們還將介紹如何使用 when 關鍵字將條件套用至 catch 區塊,以便進行更精確的錯誤處理。

本指南將提供您在編碼專案中捕捉異常、順利處理常見與複雜錯誤的方法。 我們還將探討 IronPDF 在異常處理方面的應用。

什麼是例外處理?

C# 中的例外處理是用來處理執行時錯誤、防止程式突然終止,以及在程式執行期間發生意外情況時進行管理的方法。 異常處理的核心元件包括 try, catch 以及 finally 區塊。

C# 中 Try-Catch 的基本結構;

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 區塊用於在 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 應用程式、桌面應用程式和服務。

Interlink:

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

程式碼範例

下面是一個簡單的 C# 示例,使用 IronPDF 從 HTML 創建 PDF,並針對多種類型的異常進行錯誤處理。 本範例假設您的專案已安裝 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# Catch Multiple Exceptions (How It Works For Developers):圖 1

而且是此代碼所產生的 PDF 檔案:

C# Catch Multiple Exceptions (How It Works For Developers):圖 2

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

結論

C# Catch Multiple Exceptions (How It Works For Developers):圖 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 核心程式碼庫背後的原始開發人員,他從公司成立之初就塑造了公司的產品架構,與首席執行官 Cameron Rimington 一起將公司轉型為一家 50 多人的公司,為 NASA、Tesla 和全球政府機構提供服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽工程學士學位 (BEng)(1998-2001 年)。

Jacob 於 1999 年在倫敦開設了他的第一家軟體公司,並於 2005 年創建了他的第一個 .NET 元件,之後,他專門解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF & Iron Suite for .NET 函式庫在全球的 NuGet 安裝量已超過 3000 萬次,他的基礎程式碼持續為全球使用的開發人員工具提供動力。Jacob 擁有 25 年的商業經驗和 41 年的編碼專業知識,他一直專注於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代的技術領導者。