跳過到頁腳內容
.NET幫助

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

如果你是 C# 编程的新手,你可能经常听到“try catch”语句。 在本教程中,我们将深入研究异常处理的世界,重点学习 catch 块,并探索如何使用 try 和 catch 语句使代码对错误更加具有弹性。 在此过程中,我们将提供大量现实生活中的示例来帮助巩固您的理解。

什么是异常,为什么要处理它们?

在 C# 中,异常代表程序运行时的事件,该事件干扰了程序执行指令的正常进程。 当发生异常时,程序的流程会被中断,如果没有处理异常,程序就会突然终止。

异常处理是一种预见和管理这些干扰性事件的方法,允许程序从意外问题中恢复并继续按预期运行。 通过使用 try 和 catch 块,您可以确保代码优雅地处理错误,并为用户提供有意义的反馈。

The Try Block

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 语句的一个例子:

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 块时,请始终按最具体到最通用的异常类型来排列它们。

异常过滤器为 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
$vbLabelText   $csharpLabel

在上例中,第一个 catch 块仅当异常消息包含单词“divide”时才处理DivideByZeroException。 如果条件不满足,第二个 catch 块将处理该异常。

Finally 块确保代码执行

在某些情况下,您可能希望确保执行某段代码,无论是否发生异常。 要实现这一点,您可以使用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 文件的内容。 在本节中,我们将探讨如何将 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) Figure 1

在本例中,try 块包含从 PDF 中提取文本的代码,使用 IronPDF。 如果在此过程中发生异常,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 區塊很重要,因為它確保無論是否拋出異常,特定的程式碼都會執行。這在釋放資源或執行清理任務(例如關閉文件流或數據庫連接)時特別有用。

您能否提供一個使用多個 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 關鍵字來完成的,提供了更細粒度的異常處理控制。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。