.NET 幫助

C# 捕獲多個異常(開發人員如何操作)

發佈 2024年6月6日
分享:

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

通過學習捕捉多種類型的異常,您可以針對特定問題量身定制響應,從而提高程序的可靠性。我們還將討論如何使用 when 關鍵字為 catch 塊應用條件,從而實現更精確的錯誤處理。

本指南將為您提供捕捉異常的方法,並在您的編程項目中平穩地處理常見和複雜的錯誤。我們還將探討 IronPDF 在例外處理的情境中。

什麼是例外處理?

C# 的例外處理是一種用來處理運行時錯誤的方法,可以防止程序突然終止,並在程序執行過程中管理發生的意外情況。例外處理的核心組件包括 trycatchfinally 塊。

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
VB   C#

捕捉多個異常

在現實應用中,單一操作可能會拋出各種類型的異常。為了解決這個問題,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
VB   C#

在這段程式碼中,特定異常如 IndexOutOfRangeExceptionDivideByZeroException 分別由各自的 catch 區塊捕捉。任何其他類型的異常則由通用的 Exception 捕捉區塊捕捉。

使用帶有 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
VB   C#

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
VB   C#

IronPDF 介紹

IronPDF 是一個為 C# 開發人員設計的全面性資料庫,適用於 .NET 應用程式。它幫助開發人員操作、管理和 直接從HTML創建PDF文件. 它不需要外部依赖即可工作。

您可以在不使用和安装 Adobe Acrobat 的情况下执行任何 PDF 操作。IronPDF 支持各种 PDF 功能,如编辑、合并、拆分和使用加密和数字签名保护 PDF 文档。開发人员可以在多种应用程序类型中使用 IronPDF,包括 Web 应用程序、桌面应用程序和服务。

互联:

IronPDF 的主要功能是转换 HTML轉PDF, 它保留了佈局和樣式。這非常適合從網路內容生成 PDF,無論是報告、發票還是文件。HTML 文件、網址和 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
VB   C#

代碼範例

以下是一個使用 IronPDF 從 HTML 創建 PDF 的簡單 C# 範例,並針對多種類型的異常進行錯誤處理。此範例假設您已在專案中安裝了 IronPDF。運行以下命令,在 NuGet 控制台中安裝 IronPDF:

Install-Package IronPdf

以下是程式碼:

using IronPdf;
using System;
class Program
{
    static void Main(string[] args)
    {
        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)
    {
        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)
		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
VB   C#

當我們運行此代碼時,它會在命令行中顯示此消息。

C# 捕捉多重例外(開發人員如何使用):圖 1

以下是這段代碼生成的 PDF 文件:

C# 捕捉多個異常(開發人員如何使用):圖2

確保在正確配置 IronPDF 的環境中測試這個功能,並根據您的應用程序修改 HTML 內容。這將有助於您高效管理錯誤,從而提高 PDF 生成任務的可靠性。

結論

C# 捕捉多個例外(此工作原理適用於開發人員):圖 3

在 C# 中處理多個異常是一個強大的功能,可以為您的應用程序提供強大的錯誤處理能力。通過使用多個 catch 區塊、異常過濾器和 finally 區塊,您可以創建一個有彈性且穩定的應用程序,能夠優雅地處理不同的錯誤並在各種錯誤情況下保持其完整性。

對多重異常處理的全面理解和實現確保您的應用程序能夠有效地應對意外情況。IronPDF 提供 免費試用 從 $749 開始。

< 上一頁
WebClient C#(它對開發人員的工作原理)
下一個 >
C# Lambda 表達式(它的運作方式對開發者來說)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >