一、多層異常捕獲示例1:
運行結果:
原因分析:
此題有兩個try-catch異常捕獲,第一個throw拋出的錯誤,被內層catch捕獲,故最后一個catch未捕獲,不顯示;第二個catchArithmeticException,被同名即第二個catch捕獲,顯示發生ArithmeticException。
二、多層異常捕獲示例2:
運行結果:
原因分析:
通過Debug運行分析知,當第一個throw拋出錯誤后,直接跳轉到最后一個同名的catch捕獲塊,中間程序未運行。故總結,Java中,使用try-catch語法,一旦出錯,就捕獲該錯誤;若注銷第一個throw錯誤,則會運行第二個catch,顯示發生ArithmeticException。
三、多個try-catch-finall嵌套,方法總結:
示例:
public class EmbededFinally {
public static void main(String args[]) {
int result;
try {
System.out.println("in Level 1");
try {
System.out.println("in Level 2");
// result=100/0; //Level 2
try {
System.out.println("in Level 3");
result=100/0; //Level 3
}
catch (Exception e) {
System.out.println("Level 3:" + e.getClass().toString());
}
finally {
System.out.println("In Level 3 finally");
}
// result=100/0; //Level 2
}
catch (Exception e) {
System.out.println("Level 2:" + e.getClass().toString());
}
finally {
System.out.println("In Level 2 finally");
}
// result = 100 / 0; //level 1
}
catch (Exception e) {
System.out.println("Level 1:" + e.getClass().toString());
}
finally {
System.out.println("In Level 1 finally");
}
}
}
運行結果:
原因分析:
本程序共三個try-catch-finally嵌套,每個try、catch、finally均有輸出語句。輸出順序為從第一個try開始執行三次,catch僅執行最里層level3,finally從最里層向外執行。
Finally主要用於解決資源泄露問題,它位於catch語句塊后,JVM保證它一定執行,因此從最里層執行,毫無疑問。
由於finally語塊中可能發生異常,比如此處的level3就發生java.lang.ArithmeticException異常,一旦發生此種異常,先前異常就會被拋棄,故僅僅最里層的catch捕獲到異常,之后由於異常被拋棄,level2、level3的catch並未捕捉到異常不顯示。
另外根據try-catch方法使用,try語句塊一有異常,則找相應catch捕獲經驗得知,三個try中均為異常錯誤,故依次執行try中語句塊。
四、try-catch-finally中finally不執行的特殊情況分析:
示例:
public class SystemExitAndFinally {
public static void main(String[] args)
{
try{
System.out.println("in main");
throw new Exception("Exception is thrown in main");
//System.exit(0);
}
catch(Exception e)
{
System.out.println(e.getMessage());
System.exit(0);
}
finally
{
System.out.println("in finally");
}
}
}
運行截圖:
原因分析:
通常情況下,finally運行語句一定執行,但本題中有特殊情況,在catch中有“System.exit(0);”執行此語句后,就已經結束程序,故不會運行finally語句。
五、編寫一個程序,此程序在運行時要求用戶輸入一個 整數,代表某門課的考試成績,程序接着給出“不及格”、“及格”、“中”、“良”、“優”的結論。
要求程序必須具備足夠的健壯性,不管用戶輸入什 么樣的內容,都不會崩潰。
(一)源程序:
import java.io.IOException;
import java.util.Scanner;
public class TestScore {
public static void main(String[] args)throws IOException {
// TODO Auto-generated method stub
boolean flag=true;
while(flag) {
try {
System.out.println("輸入學生分數:");
Scanner in =new Scanner(System.in);
int score=in.nextInt();
if(score<=100&&score>=0) {
//正常分數
if(score>=90) {
System.out.println("優!");
break;
}
else if(score>=80) {
System.out.println("良!");
break;
}
else if(score>=70) {
System.out.println("中!");
break;
}
else if(score>=60) {
System.out.println("及格!");
break;
}
else if(score>=0) {
System.out.println("不及格!");
break;
}
}
else//不正常int型分數
System.out.println("輸入格式錯誤,請重新輸入!");
}catch(Exception e) {
//輸入格式錯誤
System.out.println("輸入格式錯誤,請重新輸入!");
flag=true;
}
}
}
}
(二)程序結果截圖:
(三)結果分析:
(1)首先對輸入格式分析是否正確,正確繼續運行,不正確catch捕捉錯誤,通過while循環再次輸入。
(2)若輸入格式正確,但是分數不在正常范圍內,則通過if-else判定,提示再次輸入。
(3)使用if-else if()判斷分數等級。