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

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

    throw new Exception(); is something you should never do in a catch block, but you may have to or want to do throw new SomeException(throwable); (preserving the full stack trace) instead of throw throwable; in order to conform to the API of your method, e.g. when it declares to throw SomeException but you're calling code that might throw an IOException that you don't want to add to you method's throws clause.

    The probably most common case is new RuntimeException(throwable); to avoid having a throws clause altogether.

提交回复
热议问题