淺談Java的異常處理機制

Java的異常處理

今天來聊一下Java的異常處理機制,因爲我也是初學者,並沒有理解的那麼深刻,所以有什麼錯誤的話,還請多多指教。我將用五部分來解釋我所理解的Java異常。

一、異常是怎麼出現的
public class Test {
	public static void main(String[] args) {
		//寫一個會報錯的語句
		String str = null;
		System.out.println(str.length());
	}
}

運行結果
首先我們可以看到控制檯出現的:Exception in thread “main”,它是告訴我們異常信息的來源,是發生在main線程中。
然後,後面發現一個擁有描述能力的異常信息,java.lang.xxxxx一個類,這個類是幹嘛用的呢?是負責給你打印null指針異常出現的時候,紅色的異常信息。

二、用什麼來描述異常

寫錯的每一個出現異常信息的代碼,都會有一個類來進行描述,而且異常信息描述類全部以Exception結尾。
Exception:它是所有異常的根類(root)
異常信息描述類:NumberFormatException,NullPointerException等等。

三、用什麼來處理異常
try catch finally
public class Test {
	public static void main(String[] args) {
	
		try {
			//寫一個會報錯的語句
			String str = null;
			System.out.println(str.length());
		} catch (NullPointerException e) {
			System.out.println("空指針異常");
			e.printStackTrace();//打印紅色異常的方法
		}
	}
}

在這裏插入圖片描述
若try語句裏面還有其他的錯誤的話,可以用多個catch來捕獲,例如:

public class Test {
	public static void main(String[] args) {
	
		try {
			// 會報NullPointerException錯誤
			String str = null;
			System.out.println(str.length());
			// 會報NumberFormatException錯誤
			String str1 = "aaa";
			int res = 1 + Integer.parseInt(str1);
			System.out.println(res);
		} catch (NullPointerException e) {
			System.out.println("空指針異常");
			e.printStackTrace();
		} catch (NumberFormatException e) {
			System.out.println("類型轉換異常");
			e.printStackTrace();
		}
	}
}

若你不知道會報什麼錯誤,也可以使用Exception這個父類來捕獲異常。

try {
	// 會報NullPointerException錯誤
	String str = null;
	System.out.println(str.length());
	// 會報NumberFormatException錯誤
	String str1 = "aaa";
	int res = 1 + Integer.parseInt(str1);
	System.out.println(res);
} catch (Exception e) {
	System.out.println("所有異常");
	e.printStackTrace();
}

在這裏插入圖片描述
而finally是不管有沒有異常都會執行的語句,如:

try {
	// 會報NullPointerException錯誤
	String str = null;
	System.out.println(str.length());
	// 會報NumberFormatException錯誤
	String str1 = "aaa";
	int res = 1 + Integer.parseInt(str1);
	System.out.println(res);
} catch (Exception e) {
	System.out.println("所有異常");
	e.printStackTrace();
} finally {
	System.out.println("最後執行的語句");
}

在這裏插入圖片描述

四、用什麼來拋出異常
throws

首先建立一個Utils類

public class Utils {
	// throws Exception 方法中所有的異常拋出給調用者進行處理
	public void method() throws Exception{
		
		// 會報NumberFormatException錯誤
		String str1 = "aaa";
		int res = 1 + Integer.parseInt(str1);
		System.out.println(res);
	}
}

在Test類裏面來調用

public class Test {
	public static void main(String[] args) {
		
		Utils u = new Utils();
		u.method();
	}
}

在這裏插入圖片描述
這裏就需要你trycatch一下了, 如果你不想再次trycatch的話,也可以throws給調用它的類,但是這個是main方法,沒有什麼可以調用main方法,所以只能trycatch一下啦。
在這裏插入圖片描述
這裏的throws可以打一個比方,這樣更好利於理解。
就像一個人,他生病了,去看醫生, 把自己拋給了醫生,此時呢,醫生就有兩個方案,一個就是自己的能力夠用,自己能給病人看病,這就相當於用trycatch,另一個方案,就是自己的能力不夠,需要一個更有能力的大神,把病人拋給大神,這就相當於再次throws。

throw
public class Test {
	public static void main(String[] args) {
		
		throw new RuntimeException("隨時隨地拋出異常");
	}
}

在這裏插入圖片描述至此就結束了,謝謝觀看,如有什麼錯誤的話,還請多多指教。

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