如何使用 try/catch 块捕获异常How to use the try/catch block to catch exceptions

将可能引发异常的任何代码语句放置在 try 块中,将用于处理异常的语句放置在 try 块下的一个或多个 catch 块中。Place any code statements that might raise or throw an exception in a try block, and place statements used to handle the exception or exceptions in one or more catch blocks below the try block. 每个 catch 块包括异常类型,并且可以包含处理该异常类型所需的其他语句。Each catch block includes the exception type and can contain additional statements needed to handle that exception type.

在以下示例中,StreamReader 将打开一个名为 data.txt 的文件 ,并从文件中检索行。In the following example, a StreamReader opens a file called data.txt and retrieves a line from the file. 因为代码可能会引发任何三个异常,因此将其放置于 try 块中。Since the code might throw any of three exceptions, it's placed in a try block. 三个 catch 块捕获异常并通过将结果向控制台显示来处理它们。Three catch blocks catch the exceptions and handle them by displaying the results to the console.

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 块处理的异常。The Common Language Runtime (CLR) catches exceptions not handled by catch blocks. 如果异常由 CLR 捕获,则可能出现以下结果之一,具体取决于 CLR 配置:If an exception is caught by the CLR, one of the following results may occur depending on your CLR configuration:

  • 出现“调试”对话框 。A Debug dialog box appears.
  • 该程序停止执行,出现含有异常信息的对话框。The program stops execution and a dialog box with exception information appears.
  • 错误输出到标准错误输出流An error prints out to the standard error output stream.

备注

大多数代码可能会引发异常,并且一些异常(如 OutOfMemoryException)可能随时由 CLR 本身引发。Most code can throw an exception, and some exceptions, like OutOfMemoryException, can be thrown by the CLR itself at any time. 虽然应用程序无需处理这些异常,但在编写供他人使用的库时,应注意到这种可能性。While applications aren't required to deal with these exceptions, be aware of the possibility when writing libraries to be used by others. 有关何时在 try 块中设置代码的建议,请参阅异常的最佳做法For suggestions on when to set code in a try block, see Best Practices for Exceptions.

另请参阅See also