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

來源:互聯網
上載者:User

標籤:cep   數組   int   java異常處理   超出   需要   java   new   private   

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 異常,以待捕獲或繼續拋出,是因為運行時異常一旦發生,程式會停止

子父類異常問題

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

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

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

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

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();//子類的方法,

}

}

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

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.