Unchecked Exceptions

From Wikibooks, open books for an open world
< Java Programming
Jump to: navigation, search

Checked Exceptions Java Programming
Unchecked Exceptions
Preventing NullPointerException
Navigate Exceptions topic:v  d  e )

Unchecked, uncaught or runtime exceptions are exceptions that can be thrown without being caught or declared:

Example Code section 6.12: Throwing an exception without declaring it or catching it.
1 public void futureMethod() {
2   throw new RuntimeException("This method is not yet implemented");
3 }

...however, you can still declare and catch such exceptions. Runtime exceptions are not business exceptions. They are usually related to hard-coded issues like data errors, arithmetic overflow, divide by zero etc. In other words, errors that can't be worked around nor anticipated. The most famous (and feared) runtime exception is the NullPointerException.

A runtime exception must be or inherit from the RuntimeException class or the Error class.

Sometime it is desirable to catch all exceptions for logging purposes, then throw them back in. For example, in servlet programming when an application server calls the server getLastModified(), we want to monitor that no exceptions happened during the serving of the request. The application has its own logging separate from the server logging so the runtime exceptions would just go through without being detected by the application. The following code checks all exceptions, logs them and throws them back again.

Example Code section 6.13: Logging an exception.
 1 public long getLastModified(HttpServletRequest req) {
 2   try {
 3     ...
 4     return getTimeStamp();
 5     ...
 6   } catch(RuntimeException e) {
 7     log.error("Error during handling post request", e);
 9     throw e;
10   }
11 }

In the above code, all business logic exception are handled in the getTimeStamp() method. Runtime exceptions are caught for logging purposes, and then thrown back to the server to be handled.


To do:
Add some exercises like the ones in Variables

Checked Exceptions Java Programming
Unchecked Exceptions
Preventing NullPointerException