异常处理语句:throw

throw 语句用于发出在程序执行期间出现反常情况(异常)的信号。

备注

引发的异常是一个对象,该对象的类是从 System.Exception 派生的,例如:

class MyException : System.Exception {}
// ...
throw new MyException();
本在线速查手册由www.w▫3▫x▫u▫e.com提供,请勿盗用!

通常 throw 语句与 try-catch 或 try-finally 语句一起使用。

也可以用 throw 语句重新引发已捕获的异常。有关更多信息和示例,请参见 try-catch 和 引发异常

示例

此例演示如何使用 throw 语句引发异常。

C#
public class ConstTest 
{
    class SampleClass 
    {
        public int x;
        public int y;
        public const int c1 = 5;
        public const int c2 = c1 + 5;

        public SampleClass(int p1, int p2) 
        {
            x = p1; 
            y = p2;
        }
    }

    static void Main() 
    {
        SampleClass mC = new SampleClass(11, 22);   
        Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
        Console.WriteLine("c1 = {0}, c2 = {1}", 
                          SampleClass.c1, SampleClass.c2 );
    }
}
/* Output
    x = 11, y = 22
    c1 = 5, c2 = 10
 */

本在线速查手册由www.w▫3▫x▫u▫e.com提供,请勿盗用!

代码示例

请参见 try-catchtry-finally 和 try-catch-finally 示例。