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 TryCatch 區塊擷取異常
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在這個範例中,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在這個範例中,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在上面的範例中,只有當異常訊息中包含"除法"一詞時,第一個 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在上面的範例中,即使 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現在,您可以在 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在這個範例中,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在這個範例中,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
在這個範例中,try 區塊包含使用 IronPDF 從 PDF 擷取文字的程式碼。 如果過程中發生異常,catch 區塊會處理錯誤,並顯示相關訊息給使用者。
結論
透過將 IronPDF 與您的 try-catch 異常處理方法結合,您可以建立健壯的應用程式,在處理 PDF 檔案時能夠優雅地處理錯誤。 這不僅能提高應用程式的穩定性,還能提升整體的使用者體驗。
切記在使用 IronPDF 等外部函式庫時,務必考慮可能發生的異常,並使用 try 和 catch 語句適當地處理異常。 如此一來,即使在處理意料之外的問題時,也能確保您的應用程式具備彈性,且對使用者友善。
IronPdf 提供 免費試用其函式庫,讓您無需承諾即可探索其功能。 如果您在試用期後決定繼續使用 IronPDF,則許可從 $799 開始。
常見問題解答
C# 中 try-catch 區塊的作用是什麼?
C# 中的 try-catch 區塊用來處理程式執行過程中發生的異常。try 區塊包含可能拋出異常的程式碼,而 catch 區塊則包含處理錯誤的程式碼,讓程式繼續順利執行。
在 C# 中處理 PDF 時,如何實現異常處理?
在 C# 中處理 PDF 時,您可以透過在涉及 PDF 建立或操作的作業周圍使用 try-catch 區塊來實現異常處理。這可讓您捕捉並處理潛在的錯誤,例如找不到檔案或格式無效,以確保您的應用程式保持穩定。
為什麼在異常處理中使用 finally 區塊很重要?
finally 區塊非常重要,因為它可以確保特定程式碼會被執行,無論是否有異常產生。這對於釋放資源或執行清理工作(例如關閉檔案串流或資料庫連線)尤其有用。
您能提供在 C# 中使用多重 catch 區塊的範例嗎?
是的,在 C# 中,您可以使用多個 catch 區塊來處理不同類型的異常。例如,您可以使用一個 catch 區塊來處理 FileNotFoundException 以及另一個來處理 FormatException 。這樣就可以針對特定的異常類型進行更精確的錯誤處理。
IronPDF 如何與 C# 中的異常處理整合?
IronPDF 整合了 C# 中的異常處理功能,允許您在執行將 HTML 轉換為 PDF 或從 PDF 檔案中提取文字等作業時使用 try-catch 區塊。這種整合有助於管理潛在錯誤,並增強應用程式的穩健性。
在使用 IronPDF 時,您可能會遇到哪些常見的例外情況?
使用 IronPDF 工作時常見的異常可能包括 FileNotFoundException (如果檔案路徑不正確),或 InvalidOperationException (如果 PDF 內容未正確渲染)。使用 try-catch 區塊處理這些異常可以防止應用程式當機。
如何在 C# 專案中安裝 IronPDF 進行 PDF 處理?
若要在 C# 專案中安裝 IronPDF,請使用套件管理員控制台的指令 Install-Package IronPdf 或在 Visual Studio 的「管理 NuGet 套件」對話方塊中搜尋「IronPDF」。這將會在您的專案中加入必要的函式庫參考。
catch 區塊與異常篩選程式有何差異?
Catch 區塊用來處理 try 區塊中發生的異常,而異常過濾器可讓您指定在哪些條件下執行 catch 區塊。這可以使用 when 關鍵字來完成,從而對異常處理進行更仔細的控制。







