標籤:
動手動腦:多層的異常捕獲-1
閱讀以下代碼(CatchWho.java),寫出程式運行結果:
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
寫出CatchWho2.java程式啟動並執行結果
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");
}
}
}
程式結果:
辨析:finally語句塊一定會執行嗎?
請通過 SystemExitAndFinally.java樣本程式回答上述問題
public class Test {
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");
}
}
}
程式結果:
編寫一個程式,此程式在運行時要求使用者輸入一個 整數,代表某門課的考試成績,程式接著給出“不及格”、“及格”、“中”、“良”、“優”的結論。
要求程式必須具備足夠的健壯性,不管使用者輸入什 麼樣的內容,都不會崩潰。
來源程式代碼:
import java.util.Scanner;
class AException extends Exception
{
String error;
AException ()
{
error="請注意要求是輸入0~100的數字";
}
public String geterror()
{
return error;
}
}
class Test
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("請輸入考試成績(0~100):");
try
{
String s = sc.nextLine(); //讀入螢幕的類型轉換為S類型
getnum(s);//判斷是否拋出異常
}
catch (AException e)
{
System.out.println(e.geterror());
}
}
private static void getnum(String s) throws AException
{
for (int i = s.length(); --i >= 0;)
{
int chr = s.charAt(i);
if (chr < 48 || chr > 57)
{
throw new AException();
}
}
double num = Double.parseDouble(s);
if (num < 0 || num> 100)
{
throw new AException();
}
if (num>= 0 && num<= 60)
{
System.out.print("不及格");
}
else if (num >= 60 && num <= 70)
{
System.out.print("及格");
}
else if (num>= 70 && num<= 80)
{
System.out.print("中");
}
else if (num >= 80 && num <= 90)
{
System.out.print("良");
}
else
{
System.out.print("優");
}
}
}
問題解答:
只有與 finally 相對應的 try 語句塊得到執行的情況下,finally 語句塊才會執行。如果在try語句塊之前返回(return)或者拋出異常,try對應的finally語句塊就不會執行
多態與異常處理課後作業