java異常處理

java異常處理

異常:程序在運行時出現的一些不正常的情況

異常由來:對於出現的不正常的情況,java通過類進行描述,並封裝成對象。

異常分爲兩類:

一、嚴重的,由error類進行描述,一般不通過寫針對性解決代碼

二、不嚴重的,由exception類進行描述,通過寫針對性代碼解決


error類和exception類的父類都是thowable類

thowable

Error

Exception

異常代碼

class ExceptionTest{
	int[] show(int x){
		int[] a = new int[x];
		for(int i = 0 ; i < a.length ; i++){
			a[i] = i + 1;
		}
		return a;
	}
}

public class ExceptionDemo {
	public static void main(String[] args){
		int[] a = new ExceptionTest().show(-1);
		for(int i = 0 ; i < a.length ; i++){
			System.out.println(a[i] + "  ");
		}
	}
}

異常處理:

java提供了特有的語句進行處理

try{

出現異常的代碼

}catch(異常類 變量){

處理異常的代碼

}finally{

一定會執行的代碼

}


class ExceptionTest{
	int[] show(int x){
		int[] a = new int[x];
		for(int i = 0 ; i < a.length ; i++){
			a[i] = i + 1;
		}
		return a;
	}
}

public class ExceptionDemo {
	public static void main(String[] args){
		try {
			int[] a = new ExceptionTest().show(-1);
			for(int i = 0 ; i < a.length ; i++){
				System.out.println(a[i] + "  ");
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("數組長度不能爲負數");
		}
		
	}
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章