.NET 帮助

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

发布 2023年五月16日
分享:

如果您是 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
VB   C#

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
VB   C#

在本例中,try 块内的代码尝试除以零,这将产生一个 DivideByZeroException 异常。然后 catch 代码块会处理该异常,并向用户显示一条信息。

多个捕捉块处理不同的异常

有时,您的 try 代码块可能会产生不同类型的异常。在这种情况下,您可以使用多个 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 语句中添加 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#

在上例中,只有当异常消息包含 "divide "一词时,第一个 catch 块才会处理 "DivideByZeroException"。如果不满足条件,第二个捕获块将处理异常。

Finally Block 确保代码执行

在某些情况下,无论是否出现异常,您都可能希望确保执行一段特定的代码。为此,您可以使用 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 文件 字符串。由于创建 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.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >