How to handle 10 common Java exceptions – J042

by Mar 29, 2016




DeegeU Java Course

The “How to handle 10 common Java exceptions” video is part of a larger free online class called “Free Java Course Online”. You can find more information about this class on “Free Java Course Online” syllabus.

Transcript – How to handle 10 common Java exceptions

In this lesson we’re going to look at code that causes exceptions, and strategies on how to fix them. These are common Java exceptions. It’s not the list of all common exceptions though. I’m focusing this video on exceptions in the java.lang package.

ArithmeticException

I saw one tongue in cheek description of an arithmetic exception. We’re asking the computer to solve a math problem we couldn’t solve. In some ways that’s right.

An arithmetic exception happens when we try to do something wrong, like divide integers by zero. That’s the most common error. The thing that throws everyone off is, there is no exception thrown when you divide floating point numbers.

public void arithmeticExceptionExample() {
   int numer = 1;
   int denom = 0;
   System.out.println("Answer = " + (numer / denom));
}

Another place we’ll see this is using the BigDecimal class. The idea behind that class is to hold any number regardless of how big it is. Of course if we divide 1 by 3, we’ll get a repeating decimal. No computer can hold an infinite number of digits. The default for BigDecimal is to represent the class exactly. To fix this, we will need to define some type of rounding, so we need to change our division to include a precision and a rounding mode like this.

public void arithmeticExceptionExample() {
   BigDecimal a = BigDecimal.valueOf(1);
   BigDecimal b = BigDecimal.valueOf(3);
   System.out.println("Answer = " 
       + a.divide(b, 4, RoundingMode.UP));
}

In short, if we get an ArithmeticException, we’ll want to focus on why the values didn’t work. Usually the exception will give us a hint to why it failed.

ArrayIndexOutOfBoundsException

We’ve already seen this error many times. An ArrayIndexOutOfBoundsException happens when we try to access an element in an array that does not exist. So if our array is 5 elements, and we try to access the sixth element which doesn’t exist, we get this exception. It can happen when we forget to account for zero based arrays.

public void arrayIndexOutOfBoundsExceptionExample() {
    int[] array = {  2, 4, 6, 8, 10 };
    for (int i=0; i<=5; i++) {
        System.out.println("Element " + i + " is " + array[i]);
    }
}

The best way to solve this exception is to avoid accessing elements by index. We’d do that like this. If we must use indexes, we’ll want to look for off by one errors. Usually in the stopping condition of a loop. The error message tells us exactly which index failed, so it should be easy to see where our off by one error is.

ClassCastException

A ClassCastException happens when we try to cast a class as a type that isn’t a super or subtype. In our code, we told Java our object here is a String. Java assumed we knew what we were doing, but when it tried to convert an integer to a string, bad things happened. When you cast an object as a class, it really must be a super or subtype. We’ll see this when we have collections with different object types.

public void classCastExceptionExample() {
    String a = "a string";
    Object b = a;
    Integer c = (Integer) b;
}

This one is pretty easy to solve. Try to keep our collection classes homogeneous, or be very careful about casting.

ClassNotFoundException

We can force the ClassNotFoundException by calling forName in the Class class. This is a checked exception, so we have to catch it. If Java can’t find the class in our class path, it gives up and throws this error. We’d likely see this error when loading third party libraries by string name. For example, if we need to load a database driver for use with JDBC, we often just pass the class name of the driver as a string. If this class cannot be found in the classpath, we get this exception.

public void classNotFoundExceptionExample() {
    try {
        Object a = Class.forName("com.deegeu.ClassDoesntExist");
    } catch (ClassNotFoundException ce) {
        System.out.println("Can't find class. " + ce.getMessage());
    }
}

The solution is first to make sure we spelled the class name correctly. If it’s correct, we need to make sure the class or jar containing the class is in our classpath.

CloneNotSupportedException

CloneNotSupportedException happens when we call the clone method on an object that doesn’t support cloning. The clone method isn’t that common. Cloning objects has a whole list of problems. But here’s the code for cloning an object. It’s a checked exception, so we have to wrap it in a try catch.

public void cloneNotSupportedExceptionExample() {
    MainApplication app = new MainApplication();
    try {
       MainApplication b = (MainApplication) app.clone();
    } catch (CloneNotSupportedException ce) {
        System.out.println("Can't clone class. " 
                + ce.getMessage()); 
    }
}

However, if we get this error, and we did expect the class to be cloned, the likely problem is the class we’re trying to clone does not implement the Cloneable interface. It’s a marker interface, so it’s often forgotten. Java won’t let us clone something that isn’t explicitly cloneable.

IllegalArgumentException

An IllegalArgumentException happens when we pass an argument that is syntactically correct, but does not make sense in context. For example, when we call the toChars method on the Character class, we pass an integer which maps to a particular character. So if we pass it 100, it will return the character d.

public void illegalArgumentExceptionExample() {
    char[] c = Character.toChars(-1);
    System.out.println(“Character = “ + c[0]); 
}

Pass it -1, which is not a valid ASCII code, we’ll get an IllegalArgumentException. -1 is a valid integer, but not a valid number for this method. To fix this, we need to make sure the value we’re sending is a valid value.

NullPointerException

The NullPointerException is the most common Java exception. The ironic thing is, there are no pointers in Java. Only references.

public void nullPointerExceptionExample() {
    MainApplication app = null;
    app.classCastExceptionExample();
}

Anyways, this happens when you have a reference to a class that doesn’t point to anything. We might have forgotten to assign the class instance before using it. More commonly, we’re using a class instance that is a parameter to a method, and who ever called the method sent null. If there is any possibility our class instance can be null, we must always check for a value before using it. This is a best practice for defensive programing. The other way to fix this, is to use Java Optionals. We’ll have several videos on Optionals, but know for now they are a way to avoid NullPointerExceptions.

NumberFormatException

NumberFormatExceptions often turn up when we’re getting input from a user. We’ll ask the user, how old are you, and they’ll answer “strawberry”.

public void numberFormatExceptionExample() {
    Integer age = Integer.parseInt("strawberry");
    System.out.println("Next year you will be " + (age + 1));
}

When we try to turn strawberry into a number, we’ll get a NumberFormatException. This is really an exception we’ll need to handle if we can ever be uncertain of the input. It’s a good example for exception handling. Bad data from our users should not crash our application. Users always enter bad data when they can. We need to add code that prompts the user to try again, or maybe use a default value. Depends on what are our program requirements.

NoClassDefFoundError

The NoClassDefFoundError is slightly different from the ClassNotFoundException. When we got the ClassNotFoundException, we were trying to find a class by a string name. NoClassDefFoundError means Java can’t find a class at runtime that was present at compile time. The way this often happens is not all the jars required to run the Java application were included at deployment. Either the classpath is incorrect, or the class file we need is missing. I often see this error when two developers compile an application with different versions of a 3rd party library.

UnsupportedClassVersionError

This is an infuriating error that often trips up new Java programmers working in a team. What will happen is, everyone will agree to use a Java version, say Java 7. Then someone will use Java 8 for their jar anyways. When everyone using Java 7 tries to use the Java 8 jar, you’ll get the UnsupportedClassVersionError. In short a higher version of Java was used to compile the class, and we’re trying to run the class on a lower version of Java. The solution is to verify the Java compile version for our application matches the Java version we’re trying to run our application.

That’s some of the common exceptions we’ll see when creating Java programs. I’ll cover other common exceptions when we get to different Java packages.

Put any questions you have in the comments below. Liking the video helps me know what I’m doing right, so if you liked the video… you know what to do.

And with that, I’ll see you in the next tutorial!







Tools Used

  • Java
  • NetBeans

Media Credits

All media created and owned by DJ Spiess unless listed below.

  • No infringement intended

Music: Easy Jam by Kevin MacLeod is licensed under a Creative Commons Attribution license (https://creativecommons.org/licenses/by/4.0/)
Source: http://incompetech.com/music/royalty-free/index.html?isrc=USUAN1100245
Artist: http://incompetech.com/

Get the code

The source code for “How to handle 10 common Java exceptions” can be found on Github. If you have Git installed on your system, you can clone the repository by issuing the following command:

 git clone https://github.com/deege/deegeu-java-intro.git

Go to the Support > Getting the Code page for more help.

If you find any errors in the code, feel free to let me know or issue a pull request in Git.

Don’t miss another video!

New videos come out every week. Make sure you subscribe!

Comments

comments

DJ Spiess

DJ Spiess

Your personal instructor

My name is DJ Spiess and I’m a developer with a Masters degree in Computer Science working in Colorado, USA. I primarily work with Java server applications. I started programming as a kid in the 1980s, and I’ve programmed professionally since 1996. My main focus are REST APIs, large-scale data, and mobile development. The last six years I’ve worked on large National Science Foundation projects. You can read more about my development experience on my LinkedIn account.

Pin It on Pinterest

Share This