views:

75

answers:

2

I am following this great discussion at SO, titled: The case against checked exceptions , but I am unable to follow where exactly RuntimeException should be used and how it is different from normal Exceptions and its subclasses. Googling gave me a complex answer, that is, it should be used to deal with programming logic errors and should be thrown when no Exception should normally occur, such as in the default block of switch-case construct.

Can you please explain RuntimeException in greater detail here. Thanks.

+4  A: 

Quotes from Effective Java 2nd Edition, Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors

The Java programming language provides three kinds of throwables: checked exceptions, runtime exceptions, and errors. There is some confusion among programmers as to when it is appropriate to use each kind of throwable. While the decision is not always clear-cut, there are some general rules that provide strong guidance.

The cardinal rule in deciding whether to use checked exception or an unchecked one is this:

  • Use checked exceptions for conditions from which the caller can reasonably be expected to recover. By throwing a checked exception, you force the caller to handle the exception in a catch clause or to propagate it outward. Each checked exception that a method is declared to throw is therefore a potent indication to the API user that associated condition is a possible outcome of invoking the method.
  • Use runtime exceptions to indicate programming errors. The great majority of runtime exceptions indicate precondition violations. A precondition violation is simply a failure by the client of an API to adhere to the contract specified by the API specification.

Here's an example:

  • When trying to read a file of arbitrary name, the file may not exists. It's not strictly a programming error when a file does not exist (e.g. perhaps it did before but was then accidentally deleted). Clients may want to recover from this. Thus, FileNotFoundException is a checked exception.
  • If you give a null string as a filename, then NullPointerException (or perhaps an IllegalArgumentException -- another contentious debate) should be thrown. Client of the API is supposed to provide a valid string value; null isn't. As far as the API is concerned, this is a programmer error, which was easily preventable. Both of these exceptions are runtime exceptions.

Item 59: Avoid unnecessary use of checked exceptions also provides additional guidance:

Checked exceptions are a wonderful feature of the Java programming language. Unlike return codes, they force the programmer to deal with exceptional conditions, greatly enhancing reliability. That said, overuse of checked exceptions can make an API far less pleasant to use. If a method throws one or more checked exceptions, the code that invokes the method must handle the exceptions in one or more catch blocks, or it must declare that it throws the exceptions and let them propagate outward. Either way, it places a nontrivial burden on the programmer.

The burden is justified if:

  • the exceptional condition cannot be prevented by proper use of the API, and
  • the programmer using the API can take some useful action once confronted with the exception.

Unless both of these conditions hold, an unchecked exception is more appropriate.

So here's a short summary of the recommendation from Effective Java 2nd Edition:

  • Preventable exceptions that happen due to API user errors should be unchecked.
  • Exceptions that can't be handled reasonably should also be unchecked.
  • Otherwise, the exception should be checked.

See also

  • Effective Java 2nd Edition
    • Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors
    • Item 59: Avoid unnecessary use of checked exceptions
    • Item 60: Favor the use of standard exceptions
    • Item 61: Throw exceptions appropriate to the abstraction
    • Item 62: Document all exceptions thrown by each method

Technical definition

An unchecked exception is defined as RuntimeException and its subclasses, and Error and its subclasses. They do not have to be declared in a method's throws clause.

References

Related questions

polygenelubricants
+1 "Use runtime exceptions to indicate programming errors." Is probably the most useful advice.
Helper Method
+5  A: 

I am unable to follow where exactly RuntimeException should be used

That's probably because you are looking at an argument, i.e. people are disagreeing about exactly this point.

and how it is different from normal Exceptions and its subclasses.

Very simple: All subclasses of Exception (except for RuntimeException and its subclasses) are checked i.e. the compiler will reject the code unelss you catch or declare them in the method signature. However, subclasses of RuntimeException are unchecked.

Googling gave me a complex answer, that is, it should be used to deal with programming logic errors and should be thrown when no Exception should normally occur, such as in the default block of switch-case construct.

This is the conventional wisdom, which says that for everything that a program can usefully deal with, you should use checked exceptions because then the compiler will force you to deal with them. Conversely, programs can typically not deal usefully with programmer errors, thus they don't have to be checked. This is how the Java Standard API uses RuntimeException.

The discussion you linked to is sparked by the view of some people (this includes me) who think that checked exceptions lead to bad code and should therefore not be used. Since you can't disable exception checking in the compiler, the only way to do this is to use only RuntimeException and its subclasses.

One observation that IMO supports this view is that the conventional wisdom of "use unchecked exceptions only for programmer error" is in fact mainly a rationalization of backwards-reasoning: there is no code safety reason why the compiler should not force you to deal with programmer errors. However, something like NullPointerException and ArrayIndexOutOfBoundsException can crop up almost anywhere, and if those were checked, nobody would ever want to program in Java. Thus, the language designers had to make a, huh, exception for those, and make them unchecked. To explain this, they came up with the "unchecked exceptions are for programmer errors" story.

Michael Borgwardt
Good answer, but it probably should read "All subclasses of Exception - except RuntimeException - are checked" because RuntimeException is a subclass of Exception.
emory
so, if I throw a RuntimeException from a method (say, method1), can I ignore it in the method that called this method1. Because, in the case of Exceptions, method1 needs to be in a try-catch phrase or the method that called it should throw an Exception itself.
euphoria83
@emory: Right, I'll clarify that, @euphoria83: exactly.
Michael Borgwardt
@Michael: Thanks. +1.
euphoria83