系统提供的异常类也许不能很好地满足我们的需要,这时程序员可以根据需要定义自己的异常类,但定义的异常类必须继承已有的异常类。
eg:定义和使用用户自定义异常。
设计思想:在程序ConsoleApplication1中先定义了一个学生类——Student类,该类包含两个私有变量成员:name和score,分别表示学生姓名和成绩,且name的长度不超过8个字节,score的范围为[0,100];另外还包含一个方法成员f(),用于设置name和score。然后自定义一个异常类userException,当对name所赋的值的长度超过8个字节或者对score所赋的值不在[0,100]范围内时都抛出此自定义异常。关键代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class userException:Exception{
public userException() { }
public userException(string ms) : base(ms) { }
public userException(string ms, Exception inner) : base(ms, inner) { }
}
class Student {
private string name;
private double score;
public void setInfo(string name,double score) {
if(name.Length>8){
throw (new userException("姓名的长度超过了8个字节!"));
}
if(score<0||score>100){
throw (new userException("非法的分数!"));
}
this.name = name;
this.score = score;
}
}
class Program
{
static void Main(string[] args)
{
Student st = new Student();
try
{
st.setInfo("adfadfaafafafafadga", 200);
}
catch (Exception e)
{
Console.WriteLine("产生的异常:{0}", e.Message);
}
Console.ReadKey();
}
}
}
运行结果: