Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RuntimeException & Error

Tags:

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?

like image 374
Roam Avatar asked Dec 09 '13 01:12

Roam


People also ask

What is the difference between exception and RuntimeException?

Exceptions are a good way to handle unexpected events in your application flow. RuntimeException are unchecked by the Compiler but you may prefer to use Exceptions that extend Exception Class to control the behaviour of your api clients as they are required to catch errors for them to compile.

What does RuntimeException mean in Java?

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.

What causes RuntimeException in Java?

This Java runtime exception happens when the wrong type of object is placed into an array.

Can RuntimeException be caught?

Catching Exception or ThrowableCatching Exception will catch both checked and runtime exceptions. 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

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.

like image 130
Pita Avatar answered Oct 11 '22 18:10

Pita