如何显式引发异常
可使用 C# throw
或 Visual Basic Throw
语句显式引发异常。 可使用 throw
语句再次引发捕获的异常。 在编码方面,建议向再次引发的异常添加信息以在调试时提供详细信息。
下方代码示例使用 try
/catch
块来捕获可能的 FileNotFoundException。 以下 try
块为可捕获 FileNotFoundException 并在未找到数据文件时将消息写入控制台的 catch
块。 下一语句为 throw
语句,可引发新的 FileNotFoundException 并向异常添加文本信息。
var fs = default(FileStream);
try
{
// Open a text tile.
fs = new FileStream(@"C:\temp\data.txt", FileMode.Open);
var sr = new StreamReader(fs);
// Read a value 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
{
fs?.Close();
}
Option Strict On
Imports System.IO
Public Class ProcessFile
Public Shared Sub Main()
Dim fs As FileStream = Nothing
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