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

前端 未结 6 1155
失恋的感觉
失恋的感觉 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:33

    Why is not necessary to put the throws keyword on the method's signature?

    You can put that cause your // Any processing is not throwing any checked-exception.

    Example:

    This compile fine.

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

    This won't compile, you need to add throws clause.

    public void throwsOrNotThrowsThatsTheQuestion() {
        try {
            throw new Exception();
        } catch (Exception e) {
            //do something like log and rethrow
            throw e;
        }
    }
    

    This is working since java 7. In previous version an exception is thrown. More information rethrow in java 7

提交回复
热议问题