課堂代碼
public static void main(String[] args) {
int divisor = 100;
int dividend = 0;
//System.out.println(divisor / dividend);//ArinthmeticException 算數(shù)異常
try {
System.out.println(divisor / dividend);//ArinthmeticException 算數(shù)異常
} catch (Exception e) {
e.printStackTrace();
System.out.println("捕獲到一個異常");
}finally {
System.out.println("不管如何都會執(zhí)行這里的代碼");
}
System.out.println("哈哈哈哈");
}
public static void main(String[]args){
int [] a = new int[2];
Scanner scanner = new Scanner(System.in);
try{
int i = scanner.nextInt();
int j = scanner.nextInt();
a[0] = i;
a[2] = j;
System.out.println(a[0]/a[2]);
//Array INdex Outof Bounds Exception 數(shù)組 索引 超出 邊界 異常
//Input Mismatch Excepyion 輸入 不匹配 異常
//Arithmetic Exception 數(shù)學(xué)數(shù)字 異常
}catch(ArrayIndexOutOfBoundsException | InputMismatchException |ArithmeticException e){
System.out.println("數(shù)組越界異常");
System.out.println("數(shù)據(jù)格式不正確異常");
System.out.println("算數(shù)異常");
System.out.println("以上異常中的一個");
}
}
public static void main(String[]args) throws Exception{ //繼續(xù)向上聲明異常连舍,不處理
try {
setSex("雙性人");
}catch (Exception e){ //調(diào)用者處理異常
e.printStackTrace();
System.out.println("調(diào)用者說處理過了");
}
}
public static void setSex(String sex) throws Exception{ //聲明異常
if (!(sex.equals("男")||sex.equals("女"))){
throw new SexException("發(fā)現(xiàn)一個不對勁的"); //拋出異常
}
}
public SexException(){
}
public SexException(String message){
System.out.println("我是自定義的異常,非男非女孙乖,但我也沒辦法處理");
System.out.println("......");
}