문제

Is there any way to avoid a need to declare "throws" in method interface in Java?

The problem is: I have a very simple method, which throws NPE. It's very simple, and I added all possible checks, and frankly can't imagine how this can happen, so I want to investigate. I added try/catch(Throwable e) with logging and in the end want to re-throw.

This requires me to add "throws" declaration. But this method is the implementation of interface, so I need to update the interface also, and then all other implementations, and then some (probably many) usages. Is there really not any way to avoid this? What I'm about to do currently is cause native exception in the end of catch: by accessing null or by division by 0 - and this looks sooo sick!

도움이 되었습니까?

해결책

If you don't care that the original exception is preserved, you can throw a RuntimeException and wrap the original exception inside it. RuntimeException and derived exceptions are unchecked and don't need to be listed. If you need to preserve the original exception, you have to adjust the throws clause.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top