系統提供的異常類也許不能很好地滿足我們的需要,這時程式員可以根據需要定義自己的異常類,但定義的異常類必須繼承已有的異常類。
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();
}
}
}
運作結果: