Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do checked exceptions happen at run-time?

I am confused with the naming of runtime exception of java. Those checked exceptions, like SQLexception, also happen during the execution of a program. Why only those unchecked ones called runtime exception? It is probably I have misunderstanding of "runtime".

Thank you for any advices.

like image 824
paul paul Avatar asked Jun 20 '11 20:06

paul paul


2 Answers

I can understand your confusion. All exceptions occur at runtime!

The only reason I can come up with for naming the class that way, is that it clarifies that it is an exception that doesn't have to be dealt with at compile time.

As opposed to all other so called "checked" exceptions, RuntimeExceptions doesn't require the programmer to declare the exception to be thrown using a throws clause.

like image 200
aioobe Avatar answered Oct 13 '22 00:10

aioobe


RuntimeException is a subclass of java.lang.Exception. RunTimeExceptions are almost always the result of a programming error or/and invariants not being met (Nulls being passed when they shouldn't), so you do not have to catch them like java.lang.Exception (which is Checked Exceptions). You don't catch them because there's little the Run Time system could do to recover.

I think the phrase runtime just means they happen when the program is running (obviously!!) and crucially the compiler doesn't force checks to be built into the code as with Checked Exceptions. I think it's an example of where it's difficult to name a class appropriately e.g. I guess they could have Exceptions unchecked by default and called it Exception. Then subclassed it to provide CheckedException - everyone calls java.lang.Exception a Checked Exception, but it's not clear from the Class Name. But they didn't and we have:

> java.lang.Exception is referred to as "Checked Exception" 
> java.lang.RuntimeException is referred to as "Unchecked Exception"
like image 20
planetjones Avatar answered Oct 13 '22 00:10

planetjones