1.任何從Exception派生的類都可以用throw語(yǔ)句拋出,拋出例外用來(lái)表明程序遇到的錯(cuò)誤無(wú)法正常執(zhí)行而需要例外處理
throw new MyException(“some infomation”);
2.例外拋出點(diǎn)后的代碼在拋出例外后不再執(zhí)行
也可以說(shuō)例外的拋出終止了代碼段的執(zhí)行
自定義異常
不是由系統(tǒng)監(jiān)測(cè)到的異常(下標(biāo)越界,被0-除等),而是由用戶自己定義的異常.
用戶定義的異常同樣要用try--catch捕獲,但必須由用戶自己拋出 throw new MyException.
異常是一個(gè)類,用戶定義的異常必須繼承自SystemException或ApplicationException類,建議ApplicationException類.
形如:
class MyException : ApplicationException
{….}
例:
計(jì)算兩個(gè)數(shù)之和,當(dāng)任意一個(gè)數(shù)超出范圍時(shí),拋出自己的異常
public class NumberRangeException : ApplicationException
{ public NumberRangeException(String msg):base(msg)
{ }
}
public int CalcAnswer(String str1, String str2)
{
int int1, int2;
int answer = -1;
try
{
int1 = int.Parse(str1);
int2 = int.Parse(str2);
if( (int1 < 10) || (int1 > 20)|| (int2 < 10) || (int2 > 20)))
{
NumberRangeException e = new NumberRangeException
("Numbers not within the specified range.");
throw e;
}
answer = int1 + int2;
}catch (FormatException e){
Console.WriteLine(e);
}
return answer;
}
public void GetAnswer()
{
String answerStr;
try
{
int answer = CalcAnswer(“12”, “5”);
}catch (NumberRangeException e){
answerStr = e.Message;
}
Console.WriteLine(answerStr);
}