try catch 处理异常后,为什么还要加throws抛出这个异常

说实话这个问题挺憨的

catch是为这段代码捕获异常,做相应的处理。

在调用该类的上级类中,若不需要对此异常进行相应处理,则不必使用throws抛出该类的异常给上级类;

若上级类需要处理此异常,这时需要throws抛出此异常给上级类,上级类可以使用catch方法捕获此异常进行处理操作

public class ThrowDemo {
    public static void main(String[] args) {
        Demo demo=new Demo();
        demo.demo1();
        System.out.println("----------------------");
        try{
            demo.demo2();
        }catch(ArrayIndexOutOfBoundsException e){
            System.out.println("[Exception thown] "+e);
        }finally{
            System.out.println("被调用类抛出的异常传递到主类中,主类可对其进行处理");
        }
        System.out.println("----------------------");
        demo.demo3();
    }
}
class Demo{
    public void demo1(){
        try{
            throw new ArrayIndexOutOfBoundsException("异常");
        }catch(ArrayIndexOutOfBoundsException e){
            System.out.println("[Exception thown] "+e);
        }finally{
            System.out.println("Demo.demo1完成异常处理,主类调用此方法甚至不知道异常是否存在过");
        }
    }
    public void demo2() throws ArrayIndexOutOfBoundsException{
        throw new ArrayIndexOutOfBoundsException();
    }
    public void demo3() throws ArrayIndexOutOfBoundsException{
        System.out.println("这个方法没有异常,用throws抛出看看效果");
    }
}

 

 


throw和throws比较

1、throw 出现在方法体内部,而 throws 出现方法名后。
2、throw 表示抛出了异常,执行 throw 则一定抛出了某种特定异常,而 throws 表示方法执行可能会抛出异常,但方法执行并不一定发生异常。

 

posted @ 2021-08-04 09:58  二十三年蝉、  阅读(2641)  评论(0)    收藏  举报