CyberArmy Academy | Open Source Institute | CyberArmy Intelligence & Security | CyberArmy Services & Projects

[Java] Exception Handling in Java



    [Java] Exception Handling in Java [View] [Reply] [Top]
    Posted by Author SAJChurchey On 2008-05-06 14:55:24
    View and vote on the article here: Exception Handling in Java


    Exception Handling in Java

    Category
    Java
    Summary
    In the following article, you will learn the basics of catching and using exceptions in Java. In future articles, I will show you how to write your own exceptions and how to chain exceptions to make more robust applications that report more effective error messages.
    Body
    I. Introduction

    An exception is something that is thrown (or returned) 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 occurs because of an error in user input. In this particular case an ArithmeticException is thrown, and unless the programmer looks for this exception and adds code to handle it, the program will crash. It will state the exception thrown and a stack trace, but this is unhelpful to the casual user. However, 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. Many are contained in the default java.lang package, but when more functionality such as AWT, Swing, or java.io is used, the packages may also contain additional exceptions thrown by those libraries. As you start expanding functionality, it might be a good idea to look at potential exceptions in the packages and when they might be thrown in the course of your application. Here are a few examples:
    • 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 cannot find a class on which 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

    Java contains keywords used specifically in testing for and handling exceptions. The ones we will be using here are try and catch, which must be used in conjunction with one another. They work similarly to if-else:
    try{
      /*
    	Contains code to be tested
      */
    }catch(Exception e){
      /*
    	Contains code to be executed if an instance of Exception is caught
      */
    }
    The catch statement can look for all exceptions (with 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, to log stack traces transparent to the user or 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 that 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, but 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 Java.

    VI. Final Thoughts on Exceptions

    The best way to prevent your application from crashing due to exceptions is to avoid them 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 points 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 an exception, understand why it occurred and make sure that you really had considered everything. You will make far more resilient and robust applications as a result.

    Sources



     
      RE: [Java] Exception Handling in Java [View] [Reply] [Top]
      Posted by 2nd Lt Life2Atreus On 2008-06-14 19:45:37
      good ol java... this looks to be further than where i am currently at in learning but ill be back here very soon
       


CyberArmy::Forum v0.6
Generated In 0.06966 seconds


About Us | Privacy Policy | Mission Statement | Help