Unchecked Exceptions

From Wikibooks, open books for an open world
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 exception are not business exceptions. They are usually related to hard-coded issues like data errors, like arithmetic overflow, divide by zero, 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 exception for logging purposes, then throw it back on. For example, in servlet programming when application server calls the server getLastModified(), we want to monitor that no exception even runtime exception happened during serving the request. The application has its own logging separate from the server logging. The runtime exceptions would just go through without detecting it by the application. The following code would check all exceptions, log them, and throw it 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);
 8 
 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 handle it.


Clipboard

To do:
Add some exercises like the ones in Variables

Checked Exceptions Java Programming
Unchecked Exceptions
Preventing NullPointerException