Share via


如何:使用 Try/Catch 块捕捉异常

将可能引发异常的代码节放在 Try 块中,而将处理异常的代码放在 Catch 块中。 Catch 块是一系列以关键字 catch 开头的语句,语句后跟异常类型和要执行的操作。

注意注意

几乎任何代码行都可能会导致异常,尤其是公共语言运行时本身引发的异常,如 OutOfMemoryExceptionStackOverflowException。大多数应用程序不必处理这些异常,但在编写由其他人使用的库时应知道这种可能性。有关何时在 Try 块中设置代码的建议,请参见处理异常的最佳做法

下面的代码示例使用 Try/Catch 块捕捉可能的异常。 Main 方法包含带有 StreamReader 语句的 Try 块,该语句打开名为 data.txt 的数据文件并从该文件写入字符串。 Try 块后面是 Catch 块,该块捕捉 Try 块产生的任何异常。

示例

Imports System
Imports System.IO

Public Class ProcessFile
    Public Shared Sub Main()
        Try
            Dim sr As StreamReader = File.OpenText("data.txt")
            Console.WriteLine("The first line of this file is {0}", sr.ReadLine())
        sr.Close()
        Catch e As Exception
            Console.WriteLine("An error occurred: '{0}'", e)
        End Try
    End Sub
End Class
using System;
using System.IO;

public class ProcessFile
{
    public static void Main()
    {
        try
        {
            StreamReader sr = File.OpenText("data.txt");
            Console.WriteLine("The first line of this file is {0}", sr.ReadLine());
        sr.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("An error occurred: '{0}'", e);
        }
    }
}
using namespace System;
using namespace System::IO;

public ref class ProcessFile
{
public:
    static void Main()
    {
        try
        {
            StreamReader^ sr = File::OpenText("data.txt");
            Console::WriteLine("The first line of this file is {0}", sr->ReadLine());
        sr->Close();
        }
        catch (Exception^ e)
        {
            Console::WriteLine("An error occurred: '{0}'", e);
        }
    }
};

int main()
{
    ProcessFile::Main();
}

此示例阐释捕捉任何异常的基本 Catch 语句。 一般而言,好的编程做法是捕捉特定类型的异常而不是使用基本 Catch 语句。 有关捕捉特定异常的更多信息,请参见在 Catch 块中使用特定异常

请参见

任务

如何:在 Catch 块中使用特定异常

如何:显式引发异常

如何:创建用户定义的异常

如何:使用 Finally 块

其他资源

异常处理基础知识