Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use "throws RuntimeException" Java [duplicate]

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?

like image 325
MaKri Avatar asked Mar 21 '15 16:03

MaKri


People also ask

When should you throw a RuntimeException?

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.

Is it good practice to throw RuntimeException?

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.

Should I extend RuntimeException or exception?

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.

Can we throws runtime exception?

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.

What is the use of runtime 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.


2 Answers

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.

like image 87
Sebastian Brudzinski Avatar answered Oct 05 '22 23:10

Sebastian Brudzinski


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.

like image 40
Marko Topolnik Avatar answered Oct 05 '22 23:10

Marko Topolnik