I am doing a code review and I have came across this method definition:
public void something() throws RuntimeException
Is there a rational reason to write 'throws RuntimeException' in Java?
According to the Java™ Language Specification, runtime exceptions should be thrown when the caller has provided erroneous input (in essence, breached the method contract) and it would be burdensome to declare a compile time exception.
Generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you don't want to be bothered with specifying the exceptions your methods can throw.
You just need to extend Exception for a custom checked exception, or RuntimeException if it's a custom unchecked exception. In addition to that, you should follow a few best practices. They make your code easier to read and your API easier to use.
RunTimeException is an unchecked exception. You can throw it, but you don't necessarily have to, unless you want to explicitly specify to the user of your API that this method can throw an unchecked exception.
The Runtime Exception is the parent class in all exceptions of the Java programming language that are expected to crash or break down the program or application when they occur. Unlike exceptions that are not considered as Runtime Exceptions, Runtime Exceptions are never checked.
RuntimeException
is unchecked exception and therefore can be thrown from any place in the code. Saying "Hey, this method can throw RuntimeException
" and knowing that any piece of code can do so may be redundant. The only reason I can think of, you would like to make it explicit is for documentation purposes, eg. "Throws RuntimeException
when some specific thing happens", but then it probably belongs to javadoc, not to method signature.
Everything is context-dependent, of which you shared none; but on a general note in may be said that this very rarely makes sense. Methods declare unchecked exceptions for documentation purposes, but these are normally specific exceptions carrying some domain-specific meaning. Declaring to throw a completely generic unchecked exception is thus quite hard to justify, although I cannot say there is absolutely no situation where it may make sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With