Sei sulla pagina 1di 3

Exception Handling in Java By: SAJChurchey I. Introduction An exception is an error thrown by a class or method reporting an error in operation.

For example, dividing by zero is undefined in mathematics, and a calculation can fail if this winds up being the case because of an error in user input. In this particular case an ArithmeticException is thrown, and unless the programmer looks for this exception and manually puts in code to handle it, the program will crash stating the exception thrown and a stack trace, which would be unhelpful to a casual user of a Java program. If the programmer handles the exception, he could deliver a useful error to the user and return the user to the beginning of the program so that they could continue to use it. II. Common Exceptions There are many different exceptions that can be thrown by a program, and the Java API contains quite a few. A lot are contained in the default package, java.lang; however, when you start using more functionality such as AWT, Swing, or java.io, the packages may also contain additional exceptions thrown by those libraries. As you start expanding the functionality, it might be a good idea to look at potential exceptions in the package and when they might be thrown in the course of your application. Here is a primer of some:

ArithmeticException--thrown if a program attempts to perform division by zero ArrayIndexOutOfBoundsException--thrown if a program attempts to access an index of an array that does not exist StringIndexOutOfBoundsException--thrown if a program attempts to access a character at a non-existent index in a String NullPointerException--thrown if the JVM attempts to perform an operation on an Object that points to no data, or null NumberFormatException--thrown if a program is attempting to convert a string to a numerical datatype, and the string contains inappropriate characters (i.e. 'z' or 'Q') ClassNotFoundException--thrown if a program can not find a class it depends at runtime (i.e., the class's ".class" file cannot be found or was removed from the CLASSPATH) IOException--actually contained in java.io, but it is thrown if the JVM failed to open an I/O stream

As I said before, many different exceptions exist, and you should probably use your API documentation to learn about additional exceptions that may apply to your particular application. III. "Catching" Exceptions The java language contains keywords used specifically for testing for and handling exceptions. The ones we will be using here are try and catch, and they must be used in conjunction with one another. They sort of work like if-else: try{ /* Contains code to be tested */ }catch(Exception e){ /* Contains code to be executed if instanced of Exception is caught */ } The catch statement can look for all exceptions, using the Exception superclass, or it can catch a specific exception that you think could be thrown in the code you are testing with the try block. You can even have multiple catch blocks to catch and execute custom code for a number of different errors. A good thing to note would be that any particular exception that is caught is compared with each catch statement sequentially; so it is a good idea to put more generic exceptions, like Exception, towards the bottom of the list.

IV. The Throwable Superclass The catch statement also stores an instance of the exception that was caught in the variable that the programmer uses, in the previous example Exception e. While all exceptions are subclasses of Exception, Exception itself is a subclass of Throwable, which contains a nice suite of methods that you can use to get all kinds of information to report about your exceptions:

getMessage()--returns the error message reported by the exception in a String printStackTrace()--prints the stack trace of the exception to standard output, useful for debugging purposes in locating where the exception occurred printStackTrace(PrintStream s)--prints the stack trace to an alternative output stream printStackTrace(PrintWriter s)--prints the stack trace to a file, this way you can log stack traces transparent to the user or log for later reference toString()--if you just decide to print out the exception it will print out this: NAME_OF_EXCEPTION: getMessage().

Using the catch you now have control over what the error message is and where it goes. V. Effectively using try-catch In this section, I'm going to give you a few code samples on using try-catch blocks to give you an idea of the flexibility you as a programmer have over exceptions in your programs. The scenario is a user has input a file name to a program of a file that does not exist. In this scenario we are going to be using a text-based program; however, in a graphical environment you can easily use the catch block to draw dialog boxes. In the first example, we want to print a useful error message and exit the program gracefully, saving the user from the confusing stack trace with something useful: try{ BufferedReader in = new BufferedReader(new FileReader(userInput)); System.out.println(in.readLine()) }catch(IOException e){ System.err.println(e.getMessage()); System.err.println("Error: " + userInput + " is not a valid file. Please verify that the file exists and that you have access to it."); System.exit(1); } Here, System.err.println() prints the error message to standard error output which is a high priority buffer that is used to report error messages to the console. If you're being a good programmer, you have separate methods that handle the different functionality of your programs; this way you can easily start the program from a previous place in the program before an exception occurs. In this next example, the user inputs the filename through the function getUserInput() elsewhere in the program; we want to report the "helpful error message" to the user and return the user to a place where he can enter a new filename. public String getFileInput(String userInput){ try{ BufferedReader in = new BufferedReader(new FileReader(userInput)); return in.readLine(); }catch(IOException e){ System.err.println(e.getMessage()); System.err.println("Error: " + userInput + " is not a valid file. Please verify that the file exists and that you have access to it."); return getFileInput(getUserInput()); } Now you have an idea of how you can control your programs once an exception is thrown, and this should give you the basic idea of how to work with exceptions in the Java language.

VI. Final Thoughts on Exceptions The best way to prevent your application from crashing from exceptions is to avoid exceptions in the first place. It is much more costly for a system to catch and handle exceptions than to account for potential errors directly in your code. A lot of times, an exception can point to a problem in the programmer's logic rather than in the user's use of the program. You should look for the cause of exceptions, and try to understand why it occurred and make sure that you really had considered everything. You will be making far more resilient and robust applications.