java異常處理 throw RuntimeException時不需要同時方法中聲明拋出throws 異常等待調用者catch進行捕獲 子父類異常問題


package com.swift.exception1;

public class Demo_Exception {
    
    public static void main(String[] args) {
        
        int[] arr=new int[] {2,5,3,5,4};
        try {
        array(arr);
        }catch(Exception e) {
            System.out.println("解決這個異常~~");
            e.printStackTrace();
        }
    }

    private static void array(int[] arr) throws Exception{
        if(arr.length>=5) {
            throw new IndexOutOfBoundsException("數組下標越界異常拋出了~~~~~~~~");
        }
        int k=arr[6];
        System.out.println(k);
        for(int x=0;x<arr.length;x++) {
            System.out.println(arr[x]);
        }
    }
}

RuntimeException也可以給throws

非運行異常(編譯異常)throw 一定需要throws 異常,以待捕獲或繼續拋出,是因為運行時異常一旦發生,程序會停止

運行時異常 jvm會自動補throws,所以不寫也不會出錯,寫上也行

子父類異常問題

子類異常不能大於父類異常

父類無異常,子類不能有異常

父類有異常,子類可以無異常

原因是因為繼承,方法被復寫的問題造成的,多態父類引用調用的是子類被復寫的方法,

class Fu{

  public void fun() throws Exception(){

}

}

class Zi extends Fu{

  public void fun() throws Throwable(){ //大於父類異常,編譯不過

}

class Test{

  public static void main(String args[]){

  Fu f=new Zi();//父類引用調用

  f.fun();//子類的方法,

}

}

即子類異常不能超出,父類罩得住就行

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM