Welcome guest! Click here to register or login.
logo

<< Tutorial 9
Tutorial 11 >>

Exceptions

***Please register FREE to rate this tutorial***


Topics
What is an exception?
Types of exceptions
Try/Catch blocks
Defining your own exceptions
Examples
Example 1
Example 2

What is an exception?

In Java, an exception can be thought of as an error when the program is being run. There are numerous types of exceptions that may occur.

In order for an exception to be used in a program, it must throw it.

Below is a short example showing a basic exception:

public class Example{
   public static void main(String args[]){
      int x = -5;
      if(x < 0){
        throw new IllegalArgumentException("The number is too small!");
      }
      System.out.println(x);
   }
}

The above example will simply throw a new exception. In general, it is of the form:

throw new ExceptionName("Error Message");

where throw is the keyword to generate an exception; new is creating the Exception object; ExceptionName is the name of the exception (see below); and the string "Error Message" is a useful message that the user will see when the exception is thrown.

Types

In Java, there are many types of exceptions that are defined within the Java libraries. Below is chart of the most commonly seen exceptions that Java will generate.

Name
Description
IllegalArgumentException An exception to handle a problem with method or command-line arguments. One way to think of this is if the user does not give a command-line argument or the argument in a method is not in a certain range, this is the appropriate exception to be thrown.
NumberFormatException An exception to handle a problem when formatting a number(s). This is commonly seen when using any of the parseXXX methods of a certain class. Say that your string is "1234ff" and you call parseInt; when you get to the 'f', the exception will be thrown since 'f' is not a number.
ArrayIndexOutOfBoundsException The name says it all. This exception will occur when an index in an array is out of bounds in either direction (less than 0 or greater than or equal to its size).
NullPointerException Ah yes, the most commonly seen and most annoying exception of them all! This means that you are pointing at nothing (or null) perhaps in a linked list or even when dealing with a JOptionPane. The solution: a bottle of Tylenol and good debugging skills.
Exception The most general type of exceptions of them all. This will not specifically check for anything but will mean some kind of error occurred.

Try/Catch blocks

In order for you to accurately deal with exceptions, you should use what is called a try/catch block.

The most general form of the try/catch block is defined below:

try{
  //some code here
}catch(ExceptionName varName){
  //some action(s) here
}

where in the above, catch will contain the appropriate code to deal with an Exception. This may be where to print out the message or contain some other code to try and deal with the error. ExceptionName is an appropriate exception name and varName is the name of Exception object.

There is also a form of a try/catch/finally block defined below:

try{
  //some code here
}catch(ExceptionName varName){
  //some action(s) here
}finally{
  //some code here
}

What the finally will do is contain some code that whether or not an exception is thrown, that code will execute. Say that there is an IllegalArgumentException thrown; the code for the catch block will execute but immediately after that, the finally code will execute. Below is an example using both kinds of definitions.

Example 1:
Try/Catch example

Download source code here (Right click - Save Tagret As...)

public class TryExample{

   public static void main(String args[]){
        String str = "2346512aa";
        int sum = 0;

        for(int i = 0; i < str.length(); i++){
            try{
                    sum += Integer.parseInt(str.charAt(i)+"");
            }catch(NumberFormatException nfe){
                    System.out.print("Yikes!  ");
            }finally{
                    System.out.println("i= " + i);
            }
        }
        System.out.println("Sum: " + sum);
   } //main

} //class

The above program will attempt to add each digit in a numeric string. The best bet is to use a try catch block, specifically for the NumberFormatException. What will happen is when the program hits the first non-numeric character, the NumberFormatException will be thrown from the Integer wrapper class and be caught.

No matter how many times the exception is thrown and caught, he finally code will execute and simply print the loop counter. Below is the output from the above program:

i= 0
i= 1
i= 2
i= 3
i= 4
i= 5
i= 6
Yikes!  i= 7
Yikes!  i= 8
Sum: 23

Let's say that you had more than 1 catch block for the above program. What kind of exception you catch depends on where you place the catch block. Let's see a modified example of the above program.

Example 2:
Try/Catch example 2

Download source code here (Right click - Save Target As...)

public class TryExample2{
   public static void main(String args[]){
        String str = "2346512aa";
        int sum = 0;

        for(int i = 0; i <= str.length(); i++){
                try{
                        sum += Integer.parseInt(str.charAt(i) + "");
                }catch(IndexOutOfBoundsException ioe){
                        System.out.print("Regular!  ");
                }catch(NumberFormatException nfe){
                        System.out.print("Yikes!  ");
                }finally{
                        System.out.println("i= " + i);
                }
        }
        System.out.println("Sum: " + sum);
   } //main
} //class

The output is now:

i= 0
i= 1
i= 2
i= 3
i= 4
i= 5
i= 6
Yikes!  i= 7
Yikes!  i= 8
Regular!  i= 9
Sum: 23

Because of the newly placed IndexOutOfBoundsException, the NumberFormatException is checked last while the IndexOutOfBoundsException is checked first. The order of the exceptions is read from top to bottom in order.

Defining Exceptions

Using the power of inheritance, you can create your own kind of exceptions. Say that you have a program that relates to both Graduate and Undergraduate students in college. More specifically, the names of the students are being read from a text file.

Instead of throwing a general IllegalArgumentException which may apply to either the Graduate or Undergraduate classes. To solve this, you can create a useful exception called GradStudentException or UnderGradStudentException; both of which are subclasses of the IllegalArgumentException.

Below is the definition, in general, of your own exceptions:

public class NewExceptionName extends OldExceptionName{
     public NewExceptionName(String gripe){
        super(gripe); //super class: OldExceptionName
     }
}

where in the above, NewExceptionName is your own name for an exception (such as GradStudentException); OldExceptionName is the name of a current exception (such as IllegalArgumentException). There is also the constructor for the new exception to allow a String argument to describe the problem. This is passed to the super class.

Below is a new exception in regard to the student program before:

public class GradStudentException extends IllegalArgumentException{
    public GradStudentException(String gripe){ 
        super(gripe); 
    }
}

The file name for each will new exception will be NewExceptionName.java and placed in the same directory as the main program execution.


<< Tutorial 9
Tutorial 11 >>