Toolkit: A Custom Exception

     

ApplicationException.java

 

 package net.javagarage.demo.exceptions; /**<p>  * This class is a subclass of java.lang.Exception,  * and can be reused to represent any application-  * specific exceptional state. For instance, if you  * are using a database, it is not a good idea to  * allow database exceptions to bubble up to the  * user, or to require handling by more than one  * layer in your application.  * <p>  * For these reasons, you typically want to make your  * own exception wrapper that will serve to represent  * application-level exceptional states. For example,  * an online store might have a CartException that  * gets thrown explicitly if the user tries to check  * out with no items in their cart, or tries to  * specify a quantity of less than 0.  * </p>  * <p>  * Note that it is good practice to actually extend  * the functionality of a class that you extend. That  * is, you should add a method or two that is  * specific to your situation.  *  * @author eben hewitt  * @see java.lang.Throwable  * @see java.lang.Exception  **/ public class ApplicationException extends Exception { private int status; /**  * constructor no-args  */ public ApplicationException() { super(); } /**  * Overloaded constructor Exception wrapperanything  * that implements the Throwable interface  */ public ApplicationException(Throwable t) { super(t); } /** * Overloaded constructor with message describing the * exceptional state */ public ApplicationException(String message) { super("ApplicationException: " + message); } /**  * Overloaded constructor with message and  * wrapped root cause  */ public ApplicationException(String message,        Throwable cause) { super(message); initCause(cause); } /**  * Overloaded Constructor with int message if your  * underlying layer (such as a database) returns some  * meaningful integer status such as -1.  */ public ApplicationException(String message,        int status) { this(message); this.status = status; } /**  * Sets the status message  */ public void setStatus(int status) { this.status = status; } /**  * Gets the status int.  * @return int The status number  * representing some state  */ public int getStatus() { return status; } /**  * Gets the message from the root cause  * @return String The root cause message  */ public String getCauseMessage() { if(getCause() != null) { return getCause().getMessage(); } else { return "Cause unknown"; } } } 

This custom exception features a number of overloaded constructors. It is nice to provide a few overloaded constructors, because it gives the user of your API choices about how to interact with it.

Now that we've seen how to define a custom exception, let's look at how to use one. Check out ExceptionClient.java. His job is to run some code that will cause the custom exception to be thrown.

ExceptionClient.java

 

 package net.javagarage.demo.exceptions; /**<p>  * ExceptionClient is simply for testing. It is a  * main method that calls two static methods to  * demonstrate how to use custom exceptions. The  * custom exception we use is ApplicationException.  * </p>  * @author eben hewitt  * @see  * net.javagarage.demo.exceptions.ApplicationException  **/ public class ExceptionClient { /**  * In your business method, just throw exception  * wrappers. That way, you can keep your code clean,  * flexible, and easy to maintain.  * @throws ApplicationException  */ private static void testWrapper() throws ApplicationException {       try {             //do something that will generate an exception             //you don't want to proliferate             int[] nums = {1,2,3};             int x = nums[5]; // ERROR! out of bounds!       } catch(ArrayIndexOutOfBoundsException obe){             throw new ApplicationException(obe);       } } /**  * Test explicitly throwing an exception when  * something bad happens. Say we have some business  * rule where you aren't allowed to take more than 10  * consecutive holidays. We want to generate an app  * exception if someone tried to.  */private static void testExplicit(int x) throws ApplicationException {       System.out.println("You are asking for " + x +       " days off."); if (x > 10){       throw new ApplicationException(x +       " is TOO MANY DAYS!\nYou will be beaten."); } //only prints if the exception is not thrown. //if it is thrown, execution jumps out of the method //and up to where it is caught in main() System.out.println("Have a nice time!"); } /**  * Shows two different uses of your custom exception.  * Obviously, we cannot test both of these at once,  * because once an exception is printed,  * execution stops.  */ public static void main(String[] args) { //to demonstrate usage try { //1. test wrapping API exceptions //testWrapper(); /*  * calling (1) produced this output:  * Message: java.lang.ArrayIndexOutOfBoundsException: 5  */ //2. IF user does something bad, you want //to send customized notice of it testExplicit(5);//okay testExplicit(100);//EXCEPTION! } catch(ApplicationException ae){ System.out.println("Message: " + ae.getMessage()); } } } 

Here is the output result of running ExceptionClient.java as is:

 

 You are asking for 5 days off. Have a nice time! You are asking for 100 days off. Message: ApplicationException: 100 is TOO MANY DAYS! You will be beaten. 

Looking at the code, you'll notice that there is a second method defined, called testWrapper (), that catches an ArrayIndexOutOfBoundsException and simply takes that entire exception and passes it as the constructor of our custom exception. We can do that because ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException , which extends RuntimeException , which extends Throwable . Whew.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net