RuntimeException & Error

Roam picture Roam · Dec 9, 2013 · Viewed 21.2k times · Source

In the exceptions hierarchy, the descendants of RuntimeException and those of Error are runtime exceptions/errors.

The difference between the two is: Those under RuntimeException are the ones caused by poor programming/design, and those of Error are the ones that can't/shouldn't be controlled by the developer.

For coding an exception within the application, for instance, to throw an exception when something in the business logic occurs, the RuntimeException is extended.

The question is, what exactly is the difference between extending RuntimeException and extending Error-- except that extending Error is bad practice?

Answer

Pita picture Pita · Dec 9, 2013

Both Error and RuntimeException are unchecked exceptions, meaning that it indicate a flaw with the program, and usually should not be caught. (NullPointerException, IndexOutOfBoundsException, etc.)

I think the main difference between the two is that RuntimeException indicate there is a error with the program, and an Error is something that is fatal but out of the program's control. (OutOfMemorryError, ThreadDeath, etc.)

Therefore subclassing an Error is bad practice because an error is usually not something that could be fixed by your program at runtime. In your program, should you need to throw something, use an Exception.