75% developed

Unchecked Exceptions

From Wikibooks, open books for an open world
Jump to navigation Jump to search

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.
public void futureMethod() {
  throw new RuntimeException("This method is not yet implemented");
}

...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.
public long getLastModified(HttpServletRequest req) {
  try {
    ...
    return getTimeStamp();
    ...
  } catch(RuntimeException e) {
    log.error("Error during handling post request", e);

    throw e;
  }
}

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.


Clipboard

To do:
Add some exercises like the ones in Variables