-
c#语言Throw异常处理语句
throw语句用于发出在程序执行期间出现反常情况(异常)的信号。throw语句通常与try-catch或try-finally语句一起使用。可以使用throw语句显式引发异常(这里引发自定义异常)。创建用户自定义异常,好的编码方法是以“Exception”作为用户自定义异常类名的结尾。
示例 throw语句的使用
本示例通过Exception派生了一个新异常类UserEmployeeException,该类中定义了3个构造函数,每个构造函数使用不同的参数,然后再抛出自定义异常。程序代码如下。
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.IO;
namespaceClsUserExecption
{
classProgram
{
publicclassUserEmployeeException:Exception
{
privatestringerrorinfo=string.Empty;
publicUserEmployeeException()
{
}
publicUserEmployeeException(stringmessage):base(message)
{
errorinfo=message;
}
publicUserEmployeeException(stringmessage,Exception
inner):base(message,inner)
{
errorinfo=message;
inner=null;
}
}
publicstaticvoidMain()
{
try
{
thrownewUserEmployeeException("errorInfoofuse");
}
catch(UserEmployeeExceptioney)
{
Console.WriteLine("输出结果为:");
Console.WriteLine(ey.Message,ey.InnerException);
Console.Read();
}
}
}
}