throw 语句用于发出在程序执行期间出现反常情况(异常)的信号。
备注
引发的异常是一个对象,该对象的类是从
复制代码 | |
|---|---|
class MyException : System.Exception {}
// ...
throw new MyException(); | |
通常 throw 语句与 try-catch 或 try-finally 语句一起使用。当引发异常时,程序查找处理此异常的 catch 语句。
也可以用 throw 语句重新引发已捕获的异常。有关更多信息和示例,请参见 try-catch 和
示例
此例演示如何使用 throw 语句引发异常。
复制代码 | |
|---|---|
// throw example
using System;
public class ThrowTest
{
static void Main()
{
string s = null;
if (s == null)
{
throw new ArgumentNullException();
}
Console.Write("The string s is null"); // not executed
}
} | |
输出
发生
代码示例
请参见 try-catch、try-finally 和 try-catch-finally 示例。
C# 语言规范
有关更多信息,请参见 C# 语言规范中的以下各章节:
-
5.3.3.11 throw 语句
-
8.9.5 throw 语句
请参见