跳過到頁腳內容
.NET幫助

Try/Catch in C#(開發者的工作原理)

如果您是 C# 程式設計的新手,您可能聽過不少"try catch"語句這個名詞。 在本教程中,我們將深入異常處理的世界,著重於 catch 區塊,並探討如何使用 try 和 catch 語句使您的程式碼更能抵抗錯誤。 在翻譯過程中,我們會提供大量真實的範例,以協助鞏固您的理解。

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

在 C# 中,異常代表程式執行時發生的情況,它會干擾程式執行指令的標準進度。 當異常發生時,程式的流程會被轉移,如果異常未被處理,程式會突然終止。

異常處理是一種預測和管理這些破壞性事件的方法,可讓您的程式從意料之外的問題中恢復,並繼續如預期般執行。 透過使用 try 和 catch 區塊,您可以確保程式碼能夠優雅地處理錯誤,並提供使用者有意義的回饋。

嘗試區塊

try 區塊是您預期可能會產生異常的程式碼區段。 當您將程式碼包裝在 try 區塊中時,您是在告訴編譯器您想要處理該區塊中可能出現的異常。

以下是如何使用 try 區塊的基本範例:

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
$vbLabelText   $csharpLabel

Catch 區塊擷取異常

catch 語句與 try 區塊結合使用,以處理異常。 當異常發生在 try 區塊中時,程式執行會跳到適當的 catch 區塊,您可以在此指定程式應該如何回應異常。

要捕捉異常,您需要在 try 區塊之後立即建立 catch 區塊。 catch 區塊通常包含一個參數,代表捕獲的異常。

以下是執行中的 catch statement 範例:

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
$vbLabelText   $csharpLabel

在這個範例中,try 程式碼區塊內的程式碼嘗試除以零,這將產生 DivideByZeroException。 接著 catch 區塊會處理異常,並顯示一則訊息給使用者。

多個 Catch 區塊處理不同的異常

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

以下範例展示多重 catch 區塊的使用:

try
{
    int[] numbers = new int[7];
    numbers[12] = 70; // This line will throw an exception
}
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; // This line will throw an exception
}
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 ' This line will throw an exception
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
$vbLabelText   $csharpLabel

在這個例子中,try 程式碼區塊內的程式碼試圖給一個不存在的陣列索引賦值,從而產生了 IndexOutOfRangeException。 第一個 catch 區塊會處理這個特定的異常,而第二個 catch 區塊則會捕捉可能發生的任何其他異常。

請記住,當使用多重 catch 區塊時,請務必從最特殊的異常類型到最一般的異常類型順序排列。

Exception Filters 在 Catch 區塊中加入條件

Exception filters 允許您在 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
$vbLabelText   $csharpLabel

在上面的例子中,只有當異常訊息包含單字"divide"時,第一個 catch 區塊才會處理 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
$vbLabelText   $csharpLabel

在上面的範例中,即使 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
$vbLabelText   $csharpLabel

現在,您可以在 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
$vbLabelText   $csharpLabel

在這個範例中,try 程式碼區塊拋出了一個 CustomException 實例,然後 catch 程式碼區塊擷取並處理了該實例。

IronPDF:將 PDF 功能與例外處理整合在一起

進一步了解 IronPDF 是一個常用的函式庫,用於在 C# 中建立、編輯 PDF 檔案以及從 PDF 檔案中擷取內容。 在本節中,我們將探討如何將 IronPDF 與您的 try-catch 異常處理方法相整合,從而優雅地處理潛在錯誤。

安裝 IronPDF

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

Install-Package IronPdf

或者,您可以在 Visual Studio 的"管理 NuGet 套件"對話方塊中搜尋"IronPDF"。

使用 IronPDF 創建 PDF 並處理異常

假設您想要 使用 IronPDF 從 HTML 字串建立 PDF 檔案。 由於建立 PDF 的過程可能會引發異常,您可以使用 try-catch 區塊來處理它們。 以下範例顯示如何使用 IronPDF 建立 PDF 並使用 try-catch 處理異常:

using IronPdf;
using System;

try
{
    var renderer = new 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 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 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
$vbLabelText   $csharpLabel

在這個範例中,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
$vbLabelText   $csharpLabel

Try/Catch in C# (How It Works For Developers) 圖 1

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

結論

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

切記在使用 IronPDF 等外部函式庫時,務必考慮可能發生的異常,並使用 try 和 catch 語句適當地處理異常。 如此一來,即使在處理意料之外的問題時,也能確保您的應用程式具備彈性,且對使用者友善。

IronPDF 提供 免費試用其函式庫,讓您無需承諾即可探索其功能。 如果您決定在試用期結束後繼續使用 IronPDF,許可證從 $999 開始。

常見問題解答

在 C# 中,try-catch 區塊的目的是什么?

C# 中的 try-catch 區塊用於處理程式執行過程中發生的異常。try 區塊包含可能引發異常的程式碼,而 catch 區塊則包含處理錯誤的程式碼,允許程序順利運行。

在使用 C# 處理 PDF 時,如何實施異常處理?

在使用 C# 處理 PDF 時,您可以在涉及 PDF 創建或操作的操作周圍使用 try-catch 區塊來實施異常處理。這使您可以捕獲和處理潛在錯誤,例如文件未找到或格式無效,確保應用程序保持穩定。

為什麼在異常處理中使用 finally 區塊很重要?

finally 區塊很重要,因為它確保無論是否拋出異常,特定的程式碼都會執行。這在釋放資源或執行清理任務(例如關閉文件流或數據庫連接)時特別有用。

您能否提供一個使用多個 catch 區塊的 C# 範例?

是的,在 C# 中,您可以使用多個 catch 區塊來處理不同類型的異常。例如,您可能有一個 catch 區塊來處理 FileNotFoundException,另一個用於處理 FormatException。這允許針對特定異常類型提供更精確的錯誤處理。

IronPDF 如何與 C# 中的異常處理集成?

IronPDF 通過允許您在執行如將 HTML 轉換為 PDF 或從 PDF 文件中提取文本等操作時使用 try-catch 區塊,與 C# 中的異常處理集成。這種集成有助於管理潛在錯誤並增強應用程序的健壯性。

在使用 IronPDF 時可能遇到的常見異常有哪些?

使用 IronPDF 時的常見異常可能包括文件路徑不正確時的 FileNotFoundException 或 PDF 內容未正確渲染時的 InvalidOperationException。使用 try-catch 區塊來處理這些異常可以防止應用程序崩潰。

如何在 C# 項目中安裝 IronPDF 以處理 PDF?

要在 C# 項目中安裝 IronPDF,可以使用程序包管理器控制台命令 Install-Package IronPDF 或在 Visual Studio 的“管理 NuGet 程序包”對話框中搜尋 'IronPDF'。這將為您的項目添加必要的庫引用。

catch 區塊與異常篩選器有何不同?

catch 區塊用於處理在 try 區塊中發生的異常,而異常篩選器則允許您指定條件,這些條件用於決定是否执行 catch 區塊。這是通過使用 when 關鍵字來完成的,提供了更細粒度的異常處理控制。

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