.NET 幫助

C# 中的 Try/Catch(開發者的運作方式)

發佈 2023年5月16日
分享:

如果您是 C# 程式設計的新手,您可能聽說過「try catch」語句這個術語。在本教程中,我們將深入探討例外處理的世界,重點介紹 catch 區塊,並探討如何使用 try 和 catch 語句使您的程式碼更能抵抗錯誤。這過程中,我們將提供大量的現實生活中的示例來幫助加強您的理解。

什麼是例外狀況,為何要處理它們?

在 C# 中,例外狀況代表程序運行時發生的一種事件,這種事件會干擾程序執行指令的正常流程。當例外狀況發生時,程序的流程會被轉移,如果未處理該例外狀況,程序將會突然終止。

例外狀況處理是一種預期和管理這些破壞性事件的方法,允許你的程序從意外問題中恢復並繼續按預期運行。通過使用 try and catch 區塊,可以確保你的代碼優雅地處理錯誤並向用戶提供有意義的反饋。

嘗試區塊

嘗試區塊是一個你預期可能會產生例外的代碼段。當你在代碼中包裝一個嘗試區塊時,你是在告訴編譯器你想要處理在該區塊內可能出現的潛在例外。

這是一個如何使用嘗試區塊的基本範例:


    try
    {
        // Code that may generate an exception
    }
    catch (Exception ex)
    {
        // handle the exception
    }

    try
    {
        // Code that may generate an exception
    }
    catch (Exception ex)
    {
        // handle the exception
    }
Try
		' Code that may generate an exception
	Catch ex As Exception
		' handle the exception
	End Try
VB   C#

Catch block 捕捉例外

catch 語句與 try 區塊一起使用來處理例外情況。當 try 區塊中發生例外時,程式執行會跳到適當的 catch 區塊,在這裡你可以指定程式應該如何響應該例外情況。

要捕捉例外,您需要在 try 區塊之後立即創建一個 catch 區塊。 catch 區塊通常包含一個表示捕捉到的例外的參數。

以下是 catch 語句運作的範例:


    try
    {
        int result = 10/0;
    }
    catch (DivideByZeroException ex)
    {
        Console.WriteLine("An error occurred: " + ex.Message);
    }

    try
    {
        int result = 10/0;
    }
    catch (DivideByZeroException ex)
    {
        Console.WriteLine("An error occurred: " + ex.Message);
    }
Try
		Dim result As Integer = 10\0
	Catch ex As DivideByZeroException
		Console.WriteLine("An error occurred: " & ex.Message)
	End Try
VB   C#

在此範例中,try 區塊中的代碼嘗試進行除以零的操作,這將生成 DivideByZeroException。catch 區塊隨後處理該異常,向用戶顯示一則訊息。

多個 catch 區塊處理不同的例外狀況

有時候,您的 try 區塊可能會產生不同類型的例外狀況。在這種情況下,您可以使用多個 catch 區塊分別處理每種類型的例外狀況。

以下範例演示了多個 catch 區塊的使用:


    try
    {
        int [] numbers = new int [7];
        numbers [12] = 70;
    }
    catch (IndexOutOfRangeException ex)
    {
        Console.WriteLine("An index out of range error occurred: " + ex.Message);
    }
    catch (Exception e)
    {
        Console.WriteLine("An unexpected error occurred: " + e.Message);
    }

    try
    {
        int [] numbers = new int [7];
        numbers [12] = 70;
    }
    catch (IndexOutOfRangeException ex)
    {
        Console.WriteLine("An index out of range error occurred: " + ex.Message);
    }
    catch (Exception e)
    {
        Console.WriteLine("An unexpected error occurred: " + e.Message);
    }
Try
		Dim numbers(6) As Integer
		numbers (12) = 70
	Catch ex As IndexOutOfRangeException
		Console.WriteLine("An index out of range error occurred: " & ex.Message)
	Catch e As Exception
		Console.WriteLine("An unexpected error occurred: " & e.Message)
	End Try
VB   C#

在此示例中,try 區塊中的代碼嘗試為不存在的陣列索引賦值,從而生成 IndexOutOfRangeException。第一個 catch 區塊處理此特定異常,而第二個 catch 區塊捕獲可能發生的其他任何異常。

請記住,當使用多個 catch 區塊時,務必按照從最具體到最一般的異常類型排序。

異常過濾器新增條件到捕捉區塊

異常過濾器允許您新增條件到捕捉區塊,使您僅在滿足特定條件時捕捉異常。要使用異常過濾器,在您的捕捉語句中加入 when 關鍵字及條件。

以下範例展示了使用異常過濾器:


    try
    {
        int result = 10 / 0;
    }
    catch (DivideByZeroException ex) when (ex.Message.Contains("divide"))
    {
        Console.WriteLine("An error occurred: " + ex.Message);
    }
    catch (DivideByZeroException ex)
    {
        Console.WriteLine("A different divide by zero error occurred: " + ex.Message);
    }

    try
    {
        int result = 10 / 0;
    }
    catch (DivideByZeroException ex) when (ex.Message.Contains("divide"))
    {
        Console.WriteLine("An error occurred: " + ex.Message);
    }
    catch (DivideByZeroException ex)
    {
        Console.WriteLine("A different divide by zero error occurred: " + ex.Message);
    }
Try
		Dim result As Integer = 10 \ 0
	Catch ex As DivideByZeroException When ex.Message.Contains("divide")
		Console.WriteLine("An error occurred: " & ex.Message)
	Catch ex As DivideByZeroException
		Console.WriteLine("A different divide by zero error occurred: " & ex.Message)
	End Try
VB   C#

在上述範例中,第一個 catch 區塊只有在例外訊息包含「divide」這個字時才會處理 DivideByZeroException。如果條件不符合,第二個 catch 區塊將處理該例外。

最終區塊確保代碼執行

在某些情況下,您可能希望保證特定代碼被執行,無論是否發生異常。為了達到這個目的,您可以使用 finally 區塊。

finally 區塊放置在 try 和 catch 區塊之後,並且無論是否發生異常,都會執行。

以下是一個展示 finally 區塊使用的例子:


    try
    {
        int result = 10 / 2;
    }
    catch (DivideByZeroException ex)
    {
        Console.WriteLine("An error occurred: " + ex.Message);
    }
    finally
    {
        Console.WriteLine("This line will always be executed.");
    }

    try
    {
        int result = 10 / 2;
    }
    catch (DivideByZeroException ex)
    {
        Console.WriteLine("An error occurred: " + ex.Message);
    }
    finally
    {
        Console.WriteLine("This line will always be executed.");
    }
Try
		Dim result As Integer = 10 \ 2
	Catch ex As DivideByZeroException
		Console.WriteLine("An error occurred: " & ex.Message)
	Finally
		Console.WriteLine("This line will always be executed.")
	End Try
VB   C#

在上面的例子中,即使 try 區塊中的代碼沒有生成異常, finally 區塊仍然會被執行。

自定義例外:根據您的需求定制例外

有時您可能希望創建自己的自定義例外來處理程式碼中的特定例外。要做到這一點,您可以創建一個繼承自 Exception 類的新類。

以下是一個創建自定義例外的範例:


    public class CustomException : Exception
    {
        public CustomException(string errorMessage) : base(errorMessage)
        {
        }
    }

    public class CustomException : Exception
    {
        public CustomException(string errorMessage) : base(errorMessage)
        {
        }
    }
Public Class CustomException
	Inherits Exception

		Public Sub New(ByVal errorMessage As String)
			MyBase.New(errorMessage)
		End Sub
End Class
VB   C#

現在,您可以在 try 和 catch 區塊中使用此自定義異常,如下所示:


    try
    {
        throw new CustomException("This is a custom exception.");
    }
    catch (CustomException ex)
    {
        Console.WriteLine("A custom exception occurred: " + ex.Message);
    }

    try
    {
        throw new CustomException("This is a custom exception.");
    }
    catch (CustomException ex)
    {
        Console.WriteLine("A custom exception occurred: " + ex.Message);
    }
Try
		Throw New CustomException("This is a custom exception.")
	Catch ex As CustomException
		Console.WriteLine("A custom exception occurred: " & ex.Message)
	End Try
VB   C#

在此範例中,try 區塊拋出一個 CustomException 實例,之後被 catch 區塊捕捉並處理。

IronPDF:集成 PDF 功能與異常處理

IronPDF 是一個受歡迎的庫,用於在 C# 中創建、編輯和提取 PDF 文件中的內容。在本節中,我們將探討如何將 IronPDF 與您的 try-catch 異常處理方法結合,以優雅地處理潛在的錯誤。

安裝 IronPDF

要開始,您首先需要安裝 IronPDF NuGet 套件。您可以使用套件管理控制台來完成此操作:

Install-Package IronPdf

或者,您可以在 Visual Studio 的「管理 NuGet 套件」對話框中搜索「IronPDF」。

使用 IronPDF 創建 PDF 並處理異常

假設你想要 將 HTML 轉換為 PDF 文件 使用 IronPDF 創建 PDF 字串。由於創建 PDF 的過程中可能引發異常,您可以使用 try-catch 塊來處理它們。以下是一個使用 IronPDF 創建 PDF 並使用 try-catch 處理異常的範例:


    using IronPdf;
    using System;
    try
    {
        var renderer = new IronPDF.ChromePdfRenderer();
        string html = "Hello, World!";
        PdfDocument PDF = renderer.RenderHtmlAsPdf(html);
        PDF.SaveAs("output.PDF");
        Console.WriteLine("PDF created successfully.");
    }
    catch (Exception ex)
    {
        Console.WriteLine("An unexpected error occurred: " + ex.Message);
    }

    using IronPdf;
    using System;
    try
    {
        var renderer = new IronPDF.ChromePdfRenderer();
        string html = "Hello, World!";
        PdfDocument PDF = renderer.RenderHtmlAsPdf(html);
        PDF.SaveAs("output.PDF");
        Console.WriteLine("PDF created successfully.");
    }
    catch (Exception ex)
    {
        Console.WriteLine("An unexpected error occurred: " + ex.Message);
    }
Imports IronPdf
	Imports System
	Try
		Dim renderer = New IronPDF.ChromePdfRenderer()
		Dim html As String = "Hello, World!"
		Dim PDF As PdfDocument = renderer.RenderHtmlAsPdf(html)
		PDF.SaveAs("output.PDF")
		Console.WriteLine("PDF created successfully.")
	Catch ex As Exception
		Console.WriteLine("An unexpected error occurred: " & ex.Message)
	End Try
VB   C#

在此範例中,try 區塊包含使用 IronPDF 創建 PDF 的程式碼。如果在過程中發生異常,catch 區塊將處理錯誤,向使用者顯示相關的錯誤訊息。

從 PDF 中提取文字並處理例外情況

您可能也想使用 IronPDF 從 PDF 文件中提取文字。與前面的示例一樣,您可以使用 try-catch 塊來處理潛在的例外情況。

以下是使用 IronPDF 從 PDF 文件中提取文字並處理例外情況的示例:


    using IronPdf;
    using System;
    using System.IO;

    try
    {
        string pdfPath = "input.PDF";
        if (File.Exists(pdfPath))
        {
            PdfDocument PDF = PdfDocument.FromFile(pdfPath);
            string extractedText = PDF.ExtractAllText();
            Console.WriteLine("Text extracted successfully: " + extractedText);
        }
        else
        {
            Console.WriteLine("The specified PDF file does not exist.");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("An unexpected error occurred: " + ex.Message);
    }

    using IronPdf;
    using System;
    using System.IO;

    try
    {
        string pdfPath = "input.PDF";
        if (File.Exists(pdfPath))
        {
            PdfDocument PDF = PdfDocument.FromFile(pdfPath);
            string extractedText = PDF.ExtractAllText();
            Console.WriteLine("Text extracted successfully: " + extractedText);
        }
        else
        {
            Console.WriteLine("The specified PDF file does not exist.");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("An unexpected error occurred: " + ex.Message);
    }
Imports IronPdf
	Imports System
	Imports System.IO

	Try
		Dim pdfPath As String = "input.PDF"
		If File.Exists(pdfPath) Then
			Dim PDF As PdfDocument = PdfDocument.FromFile(pdfPath)
			Dim extractedText As String = PDF.ExtractAllText()
			Console.WriteLine("Text extracted successfully: " & extractedText)
		Else
			Console.WriteLine("The specified PDF file does not exist.")
		End If
	Catch ex As Exception
		Console.WriteLine("An unexpected error occurred: " & ex.Message)
	End Try
VB   C#

在 C# 中使用 Try/Catch(它如何為開發人員工作)圖 1

在此範例中,try 區塊包含使用 IronPDF 從 PDF 提取文字的程式碼。如果在此過程中發生異常,catch 區塊將處理錯誤,向使用者顯示相關訊息。

結論

通過結合 IronPDF 透過 try-catch 異常處理方法,您可以創建穩健的應用程式,在處理 PDF 檔案時優雅地處理錯誤。這不僅提高了應用程式的穩定性,還提升了整體用戶體驗。

請記住,在使用像 IronPDF 這樣的外部程式庫時,要始終考慮潛在的異常,並使用 try 和 catch 語句適當地處理它們。這樣,您可以確保應用程式在處理意外問題時具有彈性且對用戶友好。

IronPDF 提供了... 免費試用,讓您無需任何承諾即可探索其功能。如果您決定在試用期後繼續使用IronPDF,許可證起價為 $749,

< 上一頁
C# For Each(開發人員如何運作)
下一個 >
C# 擴充方法(開發人員如何使用)

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

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