Common Exceptions

The Java Exception class can be used for all types of unexpected problems. However, there are also a number of specific types of exceptions you can use instead. It’s best to throw exceptions that are specifically designed for the type of problem you’re having. It’s also best to catch specific kinds of exceptions so you don’t end up with a catch block that catches a bunch of different possible problems. Here are the most common Java exceptions:

  • IOException – input/output problems, or trouble with files
  • NullPointerException – access method/variable on a variable that has the value null (the default value for objects)
  • IllegalArgumentException – an unexpected argument value in a method
  • NumberFormatException – try to convert something that doesn’t have the right format (like converting “Bob” to an int)
  • ArrayIndexOutOfBoundsException – try to access an element beyond the bounds of an array

Now, instead of throwing/catching exceptions, you can throw/catch these more specific exceptions. For example, if we revisit the divide method:

public void divide(int a, int b) 
{
    if (b == 0) 
    {
        throw new IllegalArgumentException("Division by zero");
    }
    else return a/b;
}

Since b==0 is a bad value for the divide argument, we throw an IllegalArgumentException. Now, we can also catch an IllegalArgumentException:

int a, b;
//get user input for a and b

try 
{
    int result = divide(a, b);
    System.out.println(result);
}
catch(IllegalArgumentException e) 
{
    //will print a descriptive error message
    System.out.println(e.getMessage());
}

You can also have more than one catch block if more than one type of problem might occur. For example, if we read in a line from a file and then try to convert it to a number, there are two possible problems: there might be an error reading from the file, and there might be an error converting the input to a number. Here’s how to catch both problems:

try 
{
    //read the 1st line of nums.txt, convert it to an int
    Scanner fileIn = new Scanner(new File("nums.txt"));
    String line = fileIn.nextLine();
    int val = Integer.parseInt(line);
    System.out.printf("First number: %d%n", val);
}
catch (IOException e) 
{
    System.out.println("Error reading file.");
}
catch (NumberFormatException e) 
{
    System.out.println("1st line of file not an int.");
}

Now, we will get an error message specific to the type of problem that occurs.