Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why have a project specific RuntimeException?

Is there any point in having a com.myco.myproj.MyProjRuntimeException, which completley extends RuntimeException?

like image 352
TimP Avatar asked May 05 '09 14:05

TimP


People also ask

Why do we need runtime exception?

Runtime exceptions represent problems that are the result of a programming problem and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. With the Exceptions you must catch it explicitly because you can still do something to recover.

When should you throw runtime exception?

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 we catch RuntimeException?

Runtime exceptions represent problems that are a direct result of a programming problem, and as such shouldn't be caught since it can't be reasonably expected to recover from them or handle them.


1 Answers

Yes. Do throw unchecked exceptions, and subclass them.

There is much talk about whether checked exceptions are really any good. In a nutshell, if I throw a checked exception, does my client really have anything to do with it?

Unchecked exceptions are a good way to notify your clients about exceptional situations (including illegal pre-conditions), and yet not burdening them with the need to wrap calls to your API with try-catch blocks, which most of the time basically serve no purpose, other than debugging, tracing, etc.

So why not throw a RuntimeException? It's not elegant, and it's less readable. Make it your own exception which derives from it, even if it's for no reason other than being more specific when throwing the exception.

like image 158
Yuval Adam Avatar answered Oct 01 '22 22:10

Yuval Adam