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?
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.
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.
This Java runtime exception happens when the wrong type of object is placed into an array.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With