1. 程式人生 > >Java——使用try...catch與throws處理程式執行的異常

Java——使用try...catch與throws處理程式執行的異常

     1.異常:異常就是Java程式正在執行過程中出現的錯誤     2. 兩種處理異常的方式:try catch,throws      3.Throwable子類有Error,Exception; Exception子類有RuntimeException(執行時異常)等等...          4.  try catch finally 處理異常          try用來檢測異常,catch用來捕獲異常,finally用來釋放資源                5.throws的方式處理異常      throw:在功能方法內部出現某種情況,程式不能繼續執行,需要跳轉時,就用throw把異常物件丟擲      throw與throws的區別:          throw:用在方法體內,跟的是異常物件名;只能丟擲一個異常物件名;表示丟擲異常,有方法體內的語句處理          throws:用在方法聲明後面,跟的是異常類名;可以跟多個異常類名,由逗號隔開;表示丟擲異常,由該方法的呼叫者來處理            6.編譯時異常的丟擲,必須對其進行處理,執行時異常的丟擲可以處理也可以不處理            7.finally:被finally控制的語句體一定會執行;在執行到finally之前jvm退出了就不會執行(System.exit(0))              用於釋放資源,比如,在IO流操作和資料庫操作            8.自定義異常:取決於它的名字,為了通過名字區分到底是什麼異常,然後有針對的解決方法         9.異常類注意事項:1.子類重寫父類方法時,子類的方法必須丟擲相同的異常或父類異常的子類; 2.如果父類丟擲了多個異常,                                 子類重寫父類時,只能丟擲相同的異常或者是它的子集,子類不能丟擲父類沒有的異常;3.如果被重寫的方                         法沒有異常丟擲,那麼子類的方法絕對不可以丟擲異常,如果子類方法內有異常發生,那麼子類只能try,不能throws            10.如果該功能內部可以將問題處理,用try,如果處理不了,交由呼叫者處理,這是用throws

     11.區別:後續程式需要執行和就用try,不需要繼續執行就throws           12.alt+shift+z            try catch的快捷鍵

package pra_14;
public class J_28 {
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		Div div=new Div();
		try{		//檢測可能會發生問題的程式碼		
		int x=div.div(2, 1);
		System.out.println(x);
		}catch(ArithmeticException a){ 		//ArithmeticException a=new ArithmeticException();
			System.out.println("除數不能為0!");
		}finally{
			System.out.println("hello");
		}
		 
		//try...catch的方式處理多個異常,處理多個異常時,根據多型的原理,小的異常放在前面
		int a=10;
		int b=0;
		int[] arr={11,22,33,44};
		try{
			//System.out.println(a/b);
			//System.out.println(arr[10]);
		}catch(ArithmeticException ar){
			System.out.println("除數不能為零!");
		}catch(ArrayIndexOutOfBoundsException array){
			System.out.println("索引越界!");
		}catch(Exception e){
			System.out.println("出錯~");
		}
		
		//throws的方式處理異常
		People p=new People();
		p.setAge(-17);
		System.out.println(p.getAge());
	}
}
class People{
	private String name;
	private int age;
	public People() {
		super();
		
	}
	public People(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) throws AgeOutException {
		if(age>0&&age<150){
		this.age = age;
		}
		else{
			throw new AgeOutException("年齡非法!");
			//throw new Exception("年齡出錯了!"); 
		}
	}
	
}
//自定義異常類
class AgeOutException extends Exception{
	public AgeOutException() {
		super();
		
	}
	public AgeOutException(String message) {
		super(message);		
	}
	
}
class Div{
	public int div(int a, int b){
		return a/b;
	}
}