views:

272

answers:

4

I would like to handle errors with (unchecked) exceptions. I heared that for each kind of exception I should create a subclass of either Error or RuntimeException. What's the difference?

+6  A: 

Errors should identify programmatically unrecoverable problems (e.g. out of memory). Exceptions should identify programmatically recoverable problems which are caused by unexpected conditions outside control of code (e.g. database down). RuntimeExceptions should identify programmatically recoverable problems which are caused by faults in code flow (read: developer's faults such as null pointer, illegal argument, etc).

In your case you want to inherit from RuntimeException.

BalusC
+1  A: 

I think the JavaDocs kind of say it all:

An Error is a subclass of Throwable * that indicates serious problems that a reasonable application * should not try to catch. Most such errors are abnormal conditions. * The ThreadDeath error, though a "normal" condition, * is also a subclass of Error because most applications * should not try to catch it.

These are things like stackoverflow, out of memory... you want to extend RuntimeException.

BryanD
+1  A: 

Always use RuntimeException--I've virtually never seen a case for Error.

I've heard the same thing about creating your own exception though and I don't really understand it. Often it's useful, but I use InvalidArgumentException ALL THE TIME.

Bill K
Why not creating my own exception?When I write a catch block I would like it to deal with a specific kind of exception, don't I?
snakile
From its Javadoc: *"This exception, designed for use by the **JCA/JCE engine classes**, is thrown when an invalid parameter is passed to a method."*. Don't you actually mean `IllegalArgumentException` to be more generic?
BalusC
Yes, I do. Crap. I just wasn't thinking. I'll go back and fix it.
Bill K
You know, for an exception I throw nearly all the time, you'd think I would have gotten it right... How embarrassing.
Bill K
+1  A: 

RuntimeException is a special kind of Exception, Exceptions that compiler will not catch. Error is something that is thrown when there is some severe system problem. There is not a close relation between Error and RuntimeException. Yours seem closer to RuntimeException.

fastcodejava