0

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!

everton
  • 7,579
  • 2
  • 29
  • 42
Kurtevich
  • 345
  • 8
  • 18
  • Do not catch `Throwable` since it includes things like `VirtualMachineError`, `OutOfMemoryError`, and `ThreadDeath` which you do not want to catch or try to recover from. Just catch `Exception` or, better still in your case, `RuntimeException`. – David Conrad Dec 12 '13 at 17:58
  • @DavidConrad , you are right. I wouldn't have this problem if I caught specific NPE. – Kurtevich Dec 13 '13 at 12:06

1 Answers1

3

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.

TypeIA
  • 16,916
  • 1
  • 38
  • 52
  • 2
    Additionally, if you're only concerned with NPE, since it's a RuntimeException, you can just catch NullPointerException and then rethrow it. That won't require changing the method signature. – David Conrad Dec 12 '13 at 17:56
  • Cool, this works! Rather strange behavior as for me, that compiler "knows" about some "special" branch of inheritance that should be treated differently... I mean that's why I didn't expect this. Thanks. – Kurtevich Dec 12 '13 at 17:56
  • 1
    The compiler knows that `RuntimeException` and anything that descends from it does not need to be declared in the `throws` clause of the method. These are called "Unchecked Exceptions" in Java. – David Conrad Dec 12 '13 at 18:00
  • This sort of exception wrapping may cause purists to shriek in horror, but it's a practical workaround for Java's checked-exception issue. – seand Dec 12 '13 at 18:02