如何使用 try/catch 代码块来捕获异常

将可能引发异常的任何代码语句放在try块中,并将用于处理异常的语句放在catch块下方的一个或多个try块中。 每个 catch 块都包含异常类型,并且可以包含处理该异常类型所需的其他语句。

在以下示例中,将 StreamReader 打开一个名为 data.txt 的文件,并从该文件中检索一行。 由于代码可能会引发三个异常中的任何一个,因此它放置在块 try 中。 三 catch 个块通过向控制台显示结果来捕获异常并对其进行处理。

using System;
using System.IO;

public class ProcessFile
{
    public static void Main()
    {
        try
        {
            using (StreamReader sr = File.OpenText("data.txt"))
            {
                Console.WriteLine($"The first line of this file is {sr.ReadLine()}");
            }
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine($"The file was not found: '{e}'");
        }
        catch (DirectoryNotFoundException e)
        {
            Console.WriteLine($"The directory was not found: '{e}'");
        }
        catch (IOException e)
        {
            Console.WriteLine($"The file could not be opened: '{e}'");
        }
    }
}
Imports System.IO

Public Class ProcessFile
    Public Shared Sub Main()
        Try
            Using sr As StreamReader = File.OpenText("data.txt")
                Console.WriteLine($"The first line of this file is {sr.ReadLine()}")
            End Using
        Catch e As FileNotFoundException
            Console.WriteLine($"The file was not found: '{e}'")
        Catch e As DirectoryNotFoundException
            Console.WriteLine($"The directory was not found: '{e}'")
        Catch e As IOException
            Console.WriteLine($"The file could not be opened: '{e}'")
        End Try
    End Sub
End Class

公共语言运行时(CLR)捕获由 catch 块未处理的异常。 如果 CLR 捕获了异常,则可能会根据 CLR 配置发生以下结果之一:

  • 此时会显示 “调试 ”对话框。
  • 程序停止执行,此时会显示一个包含异常信息的对话框。
  • 将错误信息输出到 标准错误输出流

注释

大多数代码都可以引发异常,某些异常(例如 OutOfMemoryException)可以随时由 CLR 本身引发。 虽然应用程序不需要处理这些异常,但请注意编写供其他人使用的库的可能性。 有关何时在块中 try 设置代码的建议,请参阅 “异常最佳做法”。

另请参阅