异常分析
?
一、請閱讀并運行AboutException.java示例,然后通過后面的幾頁PPT了解Java中實現異常處理的基礎知識。
(1)源代碼;import?javax.swing.*;
?
class?AboutException?{
???public?static?void?main(String[]?a)?
???{
??????int?i=1,?j=0,?k;
??????k=i/j;
?
?
try
{
?
k?=?i/j;????//?Causes?division-by-zero?exception
//throw?new?Exception("Hello.Exception!");
}
?
catch?(?ArithmeticException?e)
{
System.out.println("被0除.??"+?e.getMessage());
}
?
catch?(Exception?e)
{
if?(e?instanceof?ArithmeticException)
System.out.println("被0除");
else
{??
System.out.println(e.getMessage());
?
}
}
?
?
finally
?????{
????? JOptionPane.showConfirmDialog(null,"OK");
?????}
?
??}
}
?
(2)j截圖:
二、閱讀以下代碼(CatchWho.java),寫出程序運行結果:
(1)源代碼:public?class?CatchWho?{?
????public?static?void?main(String[]?args)?{?
????????try?{?
???????????? try?{?
???????????????? throw?new?ArrayIndexOutOfBoundsException();?
???????????? }?
???????????? catch(ArrayIndexOutOfBoundsException?e)?{?
??????????????? System.out.println(??"ArrayIndexOutOfBoundsException"?+??"/內層try-catch");?
???????????? }
?
????????????throw?new?ArithmeticException();?
????????}?
????????catch(ArithmeticException?e)?{?
????????????System.out.println("發生ArithmeticException");?
????????}?
????????catch(ArrayIndexOutOfBoundsException?e)?{?
???????????System.out.println(??"ArrayIndexOutOfBoundsException"?+?"/外層try-catch");?
????????}?
????}?
}
(2)結果:
(1)源代碼:public?class?CatchWho2?{?
????public?static?void?main(String[]?args)?{?
????????try?{
???????????? try?{?
???????????????? throw?new?ArrayIndexOutOfBoundsException();?
???????????? }?
???????????? catch(ArithmeticException?e)?{?
???????????????? System.out.println(?"ArrayIndexOutOfBoundsException"?+?"/內層try-catch");?
???????????? }
????????????throw?new?ArithmeticException();?
????????}?
????????catch(ArithmeticException?e)?{?
????????????System.out.println("發生ArithmeticException");?
????????}?
????????catch(ArrayIndexOutOfBoundsException?e)?{?
????????????System.out.println(?"ArrayIndexOutOfBoundsException"?+?"/外層try-catch");?
????????}?
????}?
}
(2)結果:???
三、當有多個嵌套的try…catch…finally時,要特別注意finally的執行時機。
當有多層嵌套的finally時,異常在不同的層次拋出 ,在不同的位置拋出,可能會導致不同的finally語句塊執行順序。
finally語句塊一定執行。
四、編寫一個程序,此程序在運行時要求用戶輸入一個 整數,代表某門課的考試成績,程序接著給出“不及格”、“及格”、“中”、“良”、“優”的結論。
要求程序必須具備足夠的健壯性,不管用戶輸入什 么樣的內容,都不會崩潰。
源代碼:package?dijia;
import?java.util.Scanner;
?
public?class?Test?{
?
public?static?void?main(String[]?args)?{
Scanner?s?=?new?Scanner(System.in);
?
double?chengji;String?b;
?
try{
?b?=?s.next();
throw?new?ArithmeticException();?
?
}
catch(ArithmeticException?e){
System.out.println("不及格、及格、中、良、優");
}
?
}
?
}
(1)
(2)截圖;?????????????????????
?
???????????????????????????????
轉載于:https://www.cnblogs.com/anheidijia-123/p/6103213.html
總結
- 上一篇: 【清北学堂】 死亡(death)
- 下一篇: 学号20145209《信息安全系统设计基