跳至页脚内容
.NET 帮助

C# Try/Catch(开发者如何使用)

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

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

在C#中,异常表示程序运行时发生的事件,这会干扰程序标准的指令执行过程。 当发生异常时,程序的控制流会被转移,如果异常未被处理,程序将会突然终止。

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

Try块

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

在上述示例中,只有当异常消息包含“divide”一词时,第一个catch块才会处理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

C#中的Try/Catch(对开发者的运作方式)图1

在此示例中,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,或 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 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。