tags:

views:

189

answers:

6

I want to ask why we don't have to add try-catch block to a RuntimeException while we should do that with other exceptions?

I mean like :

public class Main {
    public static void main(String[] args) {
       throw new RuntimeException();
    }
}

Edit : when I say : throw new RuntimeException(); it is so clear that there is an exception will happen ,so why the compiler doesn't forbid that ?

+11  A: 

That's because it's an unchecked exception. It doesn't need to be explicitly declared or catched. Also see the Sun tutorial on the subject.

Update: in general, you should only throw a RuntimeException (preferably one of its subclasses listed in the javadoc) to signal that the caller is doing it wrong. I.e. passing a null argument (then throw NullPointerException), or an illegal argument (then throw IllegalArgumentException), or the method is called at the wrong moment/state (then throw IllegalStateException), etcetera. The caller is supposed to fix their code to avoid that. E.g. checking beforehand if the argument is not null, or if the argument is in correct format/syntax, or ensuring that the method is called at the right moment.

If there is a specific situation which should throw a runtime exception and you can't use one of its specific subclasses, then you are supposed to extend it and document it properly in the new exception's javadoc and in the calling method, e.g. ConfigurationException extends RuntimeException for the case that the calling code hasn't configured the application/API properly before use. This should signal the enduser (the other developer) sufficiently to take action accordingly.

In nutshell: RuntimeExceptions should identify programmatically recoverable problems which are caused by faults in code flow or configuration (read: developer's faults). Checked Exceptions should identify programmatically recoverable problems which are caused by unexpected conditions outside control of code (e.g. database down, file I/O error, wrong enduser input, etc). Errors should identify programmatically unrecoverable problems (e.g. out of memory, exception inside an initializer, etc).

BalusC
but when I say : "throw new RuntimeException();" it is so clear that there is an exception will happen ,so why the compiler doesn't forbid that ?
M.H
There is nothing morally wrong with an exception. Unchecked exceptions are intentionally not checked. Hence the name unchecked.
GregS
@M.H no it is not clear. An example is the method List.add(), a normal implementation of list, like arraylist will never throw an UnsupportedOperationException, so there is no need for it to be in the exception signature. The method Collections.asUnmodifyableList() will return a List which will throw an UnsupportedOperationException on calls to List.add. The implementation of List.add consists only of throw new UnsupportedOperationException. With only having an object of type List you can't see if the exception will be thrown and a normal list should never throw it.
josefx
@josefx yes it is not clear in most cases , but is there any ambiguity when you say "throw new RuntimeException();" ??
M.H
@M.H for the code which calls the function there is. Writing throw new UnsupportedOperationException() is the same, you know it will be thrown but does the calling code need to know? The exception signature is for the calling code and it should not have to expect that a List will throw this exception, even if it is clear for the line in UnmodifyableList.add() that there will be an exception thrown. Also the public static void main(String...) method is just a normal java function for the compiler, it can be called by other functions and may throw exceptions like any other function.
josefx
@BalusC thanks for the update, now all the picture is clear.
M.H
You're welcome.
BalusC
+2  A: 

RuntimeException, Error and their subclasses are specifically not compile-time checked - they are not part of the formal contract of the method.

See Chapter 11 in the JLS, Exceptions, in particular 11.2, Compile-time checking of Exceptions.

mdma
+2  A: 

Lets argue this way. What if NullPointerException was designed to be a compile time exception? Had it been done so, the compiler had to strictly check whether a variable is null or not. There is no way that this can be done.

public void dummyMethod(Object obj){

}

Here there is no way for the compiler to check whether the obj can be null or not. However, there has to be some error/exception has to be thrown when you have a null pointer scenario.

Bragboy
Do you claim that it would introduce some fundamental constraint if NullPointerException was a checked exception? I don't get the example you provide? It might make perfect sense for the method to accept obj == null in some implementations.
aioobe
I just wanted you to think in terms of design aspect. Its perfectly logical to have both checked and unchecked. Now, in order for the compiler to check these rules, you will have to set the 'types' of them of which RuntimeException is one and NullPointerException is a type of it. And the answer to your question is yes, its a prob when NPE is made checked. The example I have provided is to tell that the Object obj passed to the method can be and cannot be null and that this method has no idea about it. A compiler can never check such instances.
Bragboy
+1  A: 

Because it's not forbidden to throw runtime exceptions and you don't have to declare runtime exceptions. Your program is a valid Java program so the compiler has no reason to complain.

eljenso
+1  A: 

Basically an uncaught exception is just shorthand for displaying a message and terminating the application.

Why would you need to do that? In some cases you can detect that something has gone wrong, some file didn't load, an api is missing, some data is for some reason corrupted, or one of a million other things is wrong. If you don't throw an exception the application may simply crash at another point, or in the worst case, keep running while the error escalates, making it much harder to debug.

It's important to understand that one throws an exception because there is an error, the exception is not the error, it's just the messenger.

eBusiness
+1 thank you very useful answer
M.H
+1  A: 

Per language specification, unchecked exceptions are not checked at compile-time which means that the compiler does not require methods to catch or to specify (with a throws) them. Classes belonging to this category are detailed in the section 11.2 Compile-Time Checking of Exceptions of the JLS:

The unchecked exceptions classes are the class RuntimeException and its subclasses, and the class Error and its subclasses. All other exception classes are checked exception classes. The Java API defines a number of exception classes, both checked and unchecked. Additional exception classes, both checked and unchecked, may be declared by programmers. See §11.5 for a description of the exception class hierarchy and some of the exception classes defined by the Java API and Java virtual machine.

So because a RuntimeException in a unchecked exception, the compiler doesn't force you to handle it. If you want to force the caller of a piece of code to handle an exception, use a checked exception (the subclasses of Exception other than RuntimeException are all checked exception classes).

Pascal Thivent