/*
* 嵌套try/catch塊
InputMismatchException 輸入類型不匹配異常
ArithmeticException 除數爲0異常
*/import java.util.Scanner;import java.util.InputMismatchException;public class Test4 { public static void main(String [] args){ Scanner sc=new Scanner(System.in); try{ System.out.println("請輸入第一個數字"); int first=sc.nextInt(); System.out.println("請輸入第二個數字"); int second =sc.nextInt(); try{ int result=first/second; System.out.println(result); }catch(ArithmeticException e){ System.out.println(e.getMessage()); } //ArithmeticException //當出現異常的運算條件時,拋出此異常。例如,一個整數“除以零”時,拋出此類的一個實例。 }catch(InputMismatchException e){ System.out.println("輸入參數錯誤。。。。"); } }}
/*
* 邏輯錯誤異常處理異常
* throw:用於手工拋出異常獨享,方法體中編寫
Exception
*/import java.util.Scanner;public class Test6 {
public static void main(String [] args){
Scanner sc=new Scanner(System.in);
System.out.println("請輸入年齡");
int age=sc.nextInt();
try{
if(age<0||age>100){
throw (new Exception("您輸入的年齡不合法"));
}
}catch(Exception e){
System.out.println(e.getMessage());
}
System.out.println("程序結束。。。。。");
}
}
多次使用try{} catch() 獲取異常
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test5 {
public static void main(String [] args){
Scanner sc=new Scanner(System.in);
int first=0;
int second=0;
try{
System.out.println("請輸入第一個數字");
first=sc.nextInt();
System.out.println("請輸入第二個數字");
second=sc.nextInt();
}catch(InputMismatchException e){
System.out.println("參數錯誤。。。。。");
}
try{
int result=first/second;
System.out.println(result);
}catch(ArithmeticException e){
System.out.println(e.getMessage());
}
}
}