Presents your JAVA E-NEWSLETTER for October 14, 2002 <-------------------------------------------> KNOW WHEN TO REUSE EXISTING EXCEPTIONS Until you start to create your own exceptions, you're not really getting their full power, but choosing when to extend existing exceptions and when to reuse them is a fine line. The exception concept in Java is a prominent part of the Java API. With the enforced catching of many exceptions, it is a lot harder for developers to ignore their expected error-handling code. These exceptions are known as checked exceptions because developers have to check for the possibility of their being thrown each time. Developers should go further than merely handling exceptions; they should begin to create their own exception classes when application errors occur. This allows them to add new meaning to their code and to stop low-level exceptions from propagating upwards. One example of a good place to add a new type of exception would be in a graphical model of a screen. It has a fixed size and has methods to move and animate a cursor on that screen. If the programmer should move the cursor off of the screen, a BoundaryPassedException could be thrown. This would enable the programmer to realize that his or her code is not performing properly, rather than just moving the cursor off into an imaginable part of the screen. Once the decision to throw an exception is made, the developer must first consider the existing exceptions. UnsupportedOperationException is an example of an exception that should see much reuse. Developers often leave a method empty for a while because it isn't needed yet. This might be in our own custom classes or might be in some extension of a Map or List. Rather than just leaving these methods empty or returning null values, why not throw an UnsupportedOperationException to notify other developers that this method shouldn't be considered yet? Other useful exceptions to consider reusing are: * IllegalArgumentException: A bad parameter was passed in. Your method may not like negative or null values. * ParseException: Something went wrong with parsing. This exception does require you to remember the position at which the error was found. * ArithmeticException: This exception occurs when writing mathematical algorithms. This exception is a good one to throw to show that something illegal happened inside the code. Throwing your own exceptions allows you to improve the readability of your code, makes it easier for developers using your code to plan their error handling, and helps improve the basic structure of your design. By reusing exceptions from the Java libraries, we are following the basic reuse philosophy of object orientation. ----------------------------------------