JAVA異常處理:try-catch-finally和throws

JAVA異常處理:try-catch-finally和throws

異常體系結構
java.lang.Throwable
(1) java.lang.Error:一般不編寫針對性的代碼進行處理
(2)java.lang.Exception:可以進行異常處理
①編譯時異常(checked)
②運行時異常(unchecked \ RuntimeException)
在這裏插入圖片描述
異常的處理:抓拋異常
在這裏插入圖片描述
(過程一:“拋”)關於異常對象的產生:①系統自動生成的異常對象②手動生成一個異常對象,並拋出(throw)

常見的幾種異常類型:

	//**************以下是運行時異常*********
	//ArithmeticException(算術運算異常)
	@Test
	public void test6() {
		
		int a = 5;
		int b = 0;
		
		System.out.println(a/b);
	}
	
	//InputMismatchException(輸入不匹配異常)
	@Test
	public void test5() {
		Scanner scan = new Scanner(System.in);
		int number1 = scan.nextInt();
		System.out.println(number1);
		
		scan.close();
	}
	
	//NumberFormatException(數值類型異常)
	@Test
	public void test4() {
		
		String str = "abc";
		int number = Integer.parseInt(str);
		System.out.println(number);
				
	}
	
	//ClassCastExcepttion(類型轉換異常)
	@Test
	public void test3() {
		Object obj = new Date();
		String str = (String)obj;
	}
    
	//ArrayIndexOutOfBoundsException(數組角標越界)
	@Test
	public void test2() {
//		int[] arr = new int[9];
//		System.out.println(arr[9]);
		//StringIndexOutOfBoundsException
		String str = "abc";
		System.out.println(str.charAt(3));
	}
	
	//NullpointerException(空指針異常)
	@Test
	public void test1(){
		
//		int[] arr = new int[3];
//		System.out.println(arr[3]);
		String str = "abc";
		str = null;
		System.out.println(str.charAt(0));
		
	}

1.異常處理的方式一:try-catch-finally的使用:

try {
            //可能出現異常的代碼
      }catch(<u>異常類型1</u> 變量名1){
            //處理異常的方式1
      }catch(<u>異常類型2</u> 變量名2){
            // 
      }catch(<u>異常類型3</u> 變量名3){
            //處理異常的方式3
      }
      <u>...</u>
      finally {
            //一定會執行的代碼
      }

在這裏插入圖片描述
2.異常處理的方式二:throws + 異常類型:
1.“throws + 異常類型”寫在方法的聲明處,指明此方法執行時,可能會拋出的異常類型。一旦當方法執行時,出現的異常代碼處生成一個異常類的對象,此對象滿足throws後異常類型是,就會被拋出。異常代碼後續的代碼,就不再執行。
2.體會:try-catch-finally:真正將異常處理掉了
throws:只是將異常拋給了方法的調用者。並沒有真正將異常處理掉。

開發中怎麼選擇try-catch-finally還是使用throws
在這裏插入圖片描述
在這裏插入圖片描述


@學習整理

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