Rethrowing an Exception: Why does the method compile without a throws clause?

前端 未结 6 1179
失恋的感觉
失恋的感觉 2020-11-27 06:40

On the source code below I\'m rethrowing an Exception.
Why is it not necessary to put the throws keyword on the method\'s signature?

         


        
6条回答
  •  半阙折子戏
    2020-11-27 07:31

    If you thorw an checked exception you need to have it in the throws list

    public void retrhowChecked() throws Exception {
        try {
            throw new IOException();
        } catch(Exception e) {
            throw e;
        }
    }
    

    If you throw an unchecked exception you don't need to put it in the throws list, you can use this to pack a checked Exception inside an unchecked one to avoid breaking code that uses this method if you change the method in question in such a way that it after the change may produce a checked exception. But you have to be careful with that, checked Exception are there to be handled!

    public void retrhowUnchecked() {
        try {
            throw new IOException();
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
    }
    

    Read more about Exceptions here.

提交回复
热议问题