1. 程式人生 > >java異常 try-catch 和throw

java異常 try-catch 和throw

異常處理1:try和catch捕獲異常

package com.MissXu.blogTest;

import java.util.Scanner;

public class ExceptionTest {

	public static void main(String[] args) {
		
		System.out.println("---------begin---------");
		//背單詞啦:divisor被除數、dividend除數、quotient商
		try {
			Scanner scan = new Scanner(System.in);
			System.out.print("Please input the divisor :");
			int divisor = Integer.parseInt(scan.nextLine()); //接收第一個整數作為被除數
			System.out.print("Please input the dividend :");
			int dividend = Integer.parseInt(scan.nextLine()); //接收第二個整數作為除數
			int quotient = divisor / dividend; //商
			System.out.println("result : " + quotient);
		} catch (NumberFormatException e) {
			System.out.println("資料格式異常:引數必須是數字!" + e);
		}catch (ArrayIndexOutOfBoundsException e){
			System.out.println("引數個數不對,必須是兩個!" + e);
		}catch (ArithmeticException  e){
			System.out.println("除數不能為零!" + e);
		}catch(Exception e){ //為了防止漏寫一些異常,可以加上Exception,但這個Exception必須寫在最後
			System.out.println("發生了異常!" + e);
		}finally{
			System.out.println("I'll run whether there is a exception. "); //輸出證明:不管異常與否程式都運行了
		}
		
		System.out.println("---------end---------");

	}

}
異常處理2:throw向上丟擲異常

這裡是一個標準的異常處理流程示例:

package com.MissXu.blogTest;

class Math{
	public int div(int i,int j) throws Exception{
		System.out.println("--------除法之前--------");
		int t=0;
		try{	
			t=i/j;
		}catch(Exception e){
			throw e;
		}finally{
			System.out.println("--------除法之後--------");
		}
			return t;
	}
}

public class ThrowTest {
	public static void main(String[] args) {
		Math m=new Math();
		try{
			int t=m.div(10,0);
			System.out.println(t);
		}catch(Exception e){
			System.out.println(e);
		}		
	}
}