Java Programming/Unchecked Exceptions

From Wikibooks, open books for an open world
< Java Programming
Jump to: navigation, search
Navigate Exceptions topic:v  d  e )

Unchecked or uncaught exceptions are those exceptions that the application programmer did not write a catch block to handle.

The unchecked exceptions can only be the RuntimeException and its subclasses, and the class Error and its subclasses. All other exception classes must be handled, otherwise the compiler gives an error.

RuntimeException can be handled by the application programmer, but the compiler does not require it to be handled.

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 doPost(), 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.

public void doPost( HttpReguest request, HttpResponse response )
{
   try {
     ...
     handleRequest();
     ...
   } catch ( Exception e ) {
     log.error( "Error during handling post request", e );
 
     throw e;
   }
}

In the above code, all business logic exception are handled in the handleRequest() method. Runtime exceptions are caught for logging purposes, and then throw back to the server to handle it.

Personal tools
Namespaces

Variants
Actions
Navigation
Community
Toolbox
Sister projects
Print/export