跳過到頁腳內容
.NET幫助

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

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

透過學習捕捉多種類型的異常,您可以針對特定問題量身訂做回應,以提高程式的可靠性。 我們也會談到如何應用條件來捕獲帶有 when 關鍵字的程式碼區塊,從而實現更精確的錯誤處理。

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

什麼是例外處理?

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

C# 中 Try-Catch 的基本結構

try 區塊包含可能觸發異常的程式碼,而 catch 區塊則負責在異常發生時管理異常。 finally 程式碼區塊是可選的,無論是否拋出異常,都會在 try-and-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# 允許你為單一 catch 程式碼區塊定義多個 try 程式碼區塊。 每個 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 提供免費試用,從 $999 開始。

常見問題解答

在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 小時在線上。
聊天
電子郵件
打電話給我