標籤:new 拋出異常 format shu ring 情況 log cpu string
1.
程式執行結果:
也就是它根本就沒拋出異常,更別提捕獲異常了。那麼,為什麼會這樣呢?
原來,
如上面程式展示,程式運行到k=i/j;的時候,就會直接終止,根本就不會運行到監視的程式,更不會運行到捕獲的程式。
結論:程式出錯後,會自動終止,根本不會繼續往下啟動並執行。
當把上面幾行代碼注釋掉之後,結果就會一切正常。
結果:
可以看到,不光是catch裡的,就連finally裡的也都正常執行了。
2.
為什麼把類型改成double就會沒事了呢?
原因是double類型的變數在做除法運算時,是允許除數為零的。
3.
預測的結果:
ArrayIndexOutOfBoundsException/內層try-catch
發生ArithmeticException
4.
預測結果:ArrayIndexOutOfBoundsException/外層try-catch
5.
運行結果:
前三個是順序執行try裡的語句,當第三個try裡出現異常時,調到catch語句裡,執行catch裡的語句,
執行完catch之後,再順序執行下面的語句,finally被執行,
再往下,
由於沒有異常了,所以,跳過catch,執行了後面的finally,
直到最後。
結論:有異常時,就會立刻跳出,尋找catch語句處理異常,
一旦異常被處理好之後,那麼,其餘的catch語句就不會再被執行,
但是,finally語句是無論有沒有異常都會執行的語句,
當然這也不是絕對的。
6.
finally並不是所有情況都執行的,
經過我上網查資料,得知finally不執行的幾種情況:
1)在finally語句塊中發生了異常。
2)在前面的代碼中用了System.exit()退出程式。
3)程式所在的線程死亡。
4)關閉CPU。
7.
來源程式:
class IllegalFormat extends Exception{ //輸入的分數格式不正確 IllegalFormat(String m){ super(m); }}public class ShuZu { public static void main(String[] args) throws IllegalFormat { // TODO Auto-generated method stub int control=1; System.out.println("請輸入分數:"); Scanner input= new Scanner(System.in); String score=new String (); //分數 score=input.next(); // 輸入分數 char score1[]=new char [100]; score1=score.toCharArray(); int i; while(control==1){ try{ for( i=0;i<score.length();i++){ if(score1[i]<48||score1[i]>57){ throw new IllegalFormat("您輸入的分數格式不正確,應為整數格式,請重新輸入:"); } } control=0; } catch(IllegalFormat e){ System.out.println(e); score=input.next(); score1=score.toCharArray(); } } int score2=Integer.parseInt(score); System.out.println("這個同學:"); if(score2>=0&&score2<60){ System.out.println("不及格。"); } else if(score2>=60&&score2<70){ System.out.println("及格。"); } else if(score2>=70&&score2<80){ System.out.println("中。"); } else if(score2>=80&&score2<90){ System.out.println("良"); } else if(score2>=90){ System.out.println("優。"); }
程式結果:
09-JAVA中的異常處理