RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Concentrate on the Java Exceptions that Matter to Your Application : Page 3

Using custom exceptions that separate application from system exceptions enables you to concentrate on handling only the exceptions that are meaningful to your application.


Mapping Business Exceptions to Java's Exceptions

Application and system exceptions can be mapped to Java exceptions using the following two custom exceptions:
  1. ApplicationException (see Listing 3): All exceptions that make sense from a business perspective are wrapped in this exception. It extends java.lang.Exception, which means that it has to be handled by the developer with a proper try/catch. These are the exceptions that a developer should worry about. When you develop a method that throws ApplicationException, developers are forced to handle this exception.
    Listing 3: ApplicationException Has Error Codes Representing
    Common Database Operations Problems
    public class ApplicationException extends Exception { public static final int UNIQUE_KEY = 1; public static final int ROW_NOT_FOUND = 2; private int code; public ApplicationException( int code ) { this.code= code; } public ApplicationException( String msg ) { super( msg ); } public ApplicationException( int code , String msg ) { super( msg ); this.code= code; } public int getCode() { return code; } }

  2. SystemException (see Listing 4): This exception extends java.lang.RuntimeException. All exceptions classified as system exceptions will be replaced by this exception. Because it extends java.lang.RuntimeException, handling it is not forced by the compiler: you handle it wherever it is suitable in your application. Please note that SystemException stores the original Exception, which can be used later on for further information.
    Listing 4: SystemException Stores the Root Cause of the Problem
    public class SystemException extends RuntimeException { public SystemException( Throwable cause ) { super( cause ); } }

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date