如何显式引发异常How to explicitly throw exceptions

可使用 C# throw 或 Visual Basic Throw 语句显式引发异常。You can explicitly throw an exception using the C# throw or the Visual Basic Throw statement. 可使用 throw 语句再次引发捕获的异常。You can also throw a caught exception again using the throw statement. 向重新引发的异常添加信息以在调试时提供详细信息,这是很好的编码做法。It is good coding practice to add information to an exception that is re-thrown to provide more information when debugging.

下方代码示例使用 try/catch 块来捕获可能的 FileNotFoundExceptionThe following code example uses a try/catch block to catch a possible FileNotFoundException. 以下 try 块为可捕获 FileNotFoundException 并在未找到数据文件时将消息写入控制台的 catch 块。Following the try block is a catch block that catches the FileNotFoundException and writes a message to the console if the data file is not found. 下一语句为 throw 语句,可引发新的 FileNotFoundException 并向异常添加文本信息。The next statement is the throw statement that throws a new FileNotFoundException and adds text information to the exception.

using System;
using System.IO;

public class ProcessFile
{
    public static void Main()
    {
        FileStream fs;
        try
        {
            // Opens a text tile.
            fs = new FileStream(@"C:\temp\data.txt", FileMode.Open);
            var sr = new StreamReader(fs);

            // A value is read from the file and output to the console.
            string line = sr.ReadLine();
            Console.WriteLine(line);
        }
        catch(FileNotFoundException e)
        {
            Console.WriteLine($"[Data File Missing] {e}");
            throw new FileNotFoundException(@"[data.txt not in c:\temp directory]", e);
        }
        finally
        {
            if (fs != null)
                fs.Close();
        }
    }
}
Option Strict On

Imports System.IO

Public Class ProcessFile

    Public Shared Sub Main()
        Dim fs As FileStream
        Try
            ' Opens a text file.
            fs = New FileStream("c:\temp\data.txt", FileMode.Open)
            Dim sr As New StreamReader(fs)

            ' A value is read from the file and output to the console.
            Dim line As String = sr.ReadLine()
            Console.WriteLine(line)
        Catch e As FileNotFoundException
            Console.WriteLine($"[Data File Missing] {e}")
            Throw New FileNotFoundException("[data.txt not in c:\temp directory]", e)
        Finally
            If fs IsNot Nothing Then fs.Close()
        End Try
    End Sub
End Class

请参阅See also