tags:

views:

467

answers:

4

Ok Ill admit I haven't done too much research on this yet, shame on me. It's almost 1 am though and i`m getting lazy to read heh.

Someone please explain the difference between java.lang.RuntimeException and java.lang.Exception? How do I decide which one to extend if I create my own exception?

(I`m C++ programmer learning Java)

THANK YOU! for the quick answers! Now I can go bed cus i choose which exception to use lol!

+6  A: 

An Exception is checked, and a RuntimeException is unchecked.

Checked means that the compiler requires that your handle the exeception in a catch, or declare your method as throwing it (or one of it's ancestors).

Generally, throw a checked exception if the caller of the API is expected to handle the exception, and an unchecked exception if it is something the caller would not normally be able to handle, such as an error with one of the parameters, i.e. a programming mistake.

Software Monkey
+13  A: 

In Java, there are two types of exceptions: checked exceptions and un-checked exceptions. A checked exception must be handled explicitly by the code, whereas, an un-checked exception does not need to be explicitly handled.

For checked exceptions, you either have to put a try/catch block around the code that could potentially throw the exception, or add a "throws" clause to the method, to indicate that the method might throw this type of exception (which must be handled in the calling class or above).

Any exception that derives from "Exception" is a checked exception, whereas a class that derives from RuntimeException is un-checked. RuntimeExceptions do not need to be explicitly handled by the calling code.

Andy White
+5  A: 

Generally RuntimeExceptions are exceptions that can be prevented programmatically. E.g NullPointerException, ArrayIndexOutOfBoundException. If you check for null before calling any method, NullPointerException would never occur. Similarly ArrayIndexOutOfBoundException would never occur if you check the index first. RuntimeException are not checked by the compiler, so it is clean code.

EDIT : These days people favor RuntimeException because the clean code it produces. It is totally a personal choice.

fastcodejava
+1  A: 
sateesh