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

}

}

即子类异常不能超出,父类罩得住就行