Java Exception Handling

Java Exception Handling – NumberFormatException

Making our way through our in-depth Java Exception Handling series, today we’re taking a look at the java.lang.NumberFormatException. As you may suspect, the NumberFormatException is thrown when code attempts to convert an invalid String into one of the other generic numeric wrapper classes, such as Integer, Byte, Long, and so forth.

Throughout this article we’ll explore the java.lang.NumberFormatException in greater detail, looking at where it resides in the Java Exception Hierarchy, as well as looking at some basic and functional sample code that illustrates how NumberFormatExceptions might be commonly thrown. Let’s get going!

The Technical Rundown

Full Code Sample

Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.

When Should You Use It?

The abstract Number class is the core superclass that is used to represent numeric values which can be converted into the primitive types of byte, double, float, int, long, and short. As such, Java throws a java.lang.NumberFormatException when a failed attempt is made to convert into one of those types. In addition, each of the numeric primitive types has its own wrapper class, namely Byte, Double, Float, Integer, Long, and Short. Like most wrappers, these classes can be used to represent a value object of the underlying primitive type, while also providing additional functionality and methods (such as the MAX_VALUE field).

For our sample code we’re testing conversion from String to each of the wrapper class types using their built in parseType() method (e.g. Integer.parseInt() for the Integer class). Just to keep things tidy we’ll traverse through them in alphabetical order, starting with Byte, which we test in the convertStringToByte(String string) method:

As you can see, nothing fancy going on here. We merely take our passed String parameter and attempt to parse it via Byte.parseByte(String string). If we catch an Exception we output it.

To call this method we have two different String values we’re trying: 20 and 200.

As you’re probably aware, the maximum positive value of a Byte is 127, so the first call works, but the second throws a java.lang.NumberFormatException, indicating that the value of 200 is out of range:

Next we have our Double testing method and executing code:

Here we’re trying three different values to show how we can use those build-in fields, like Double.MAX_VALUE. However, an unrecognizable character of x at the end of our third String value results in another java.lang.NumberFormatException:

Here’s our test for conversion to a Float object:

Our first value call works fine, as does the second, except the output is Infinity. This is because the maximum positive value of a Float is a little less than 2^39, so while there’s no parse error, a Float object cannot handle that value so it wraps to an infinite representation. Our third call, however, again uses an invalid character of x instead of the exponent e, so another NumberFormatException is thrown:

For our Integer test we again use an invalid character of x:

As expected, the second call throws another NumberFormatException:

Next we have the Long value, which is essentially just the much larger form of an Integer:

As you can see by the comment, the maximum positive value of a Long is 2e63 - 1, which we’ve converted to its decimal format as a String. Both these first two conversions work fine, but increasing the value to one above the MAX_VALUE produces another NumberFormatException:

Finally, we have the Short conversion. While Long is a much larger Integer, Short is limited to a far smaller value:

Again we’re testing using the maximum positive value of a Short (32,767), which works fine, but the increase to one more than that throws yet another NumberFormatException:

As we can see, NumberFormatExceptions can occur in a variety of scenarios, but typically they’re due to either typos in the numeric String values that are being parsed, or because the resultant value would exceed the bounds of the target object type.

The Airbrake-Java library provides real-time error monitoring and automatic exception reporting for all your Java-based projects. Tight integration with Airbrake’s state of the art web dashboard ensures that Airbrake-Java gives you round-the-clock status updates on your application’s health and error rates. Airbrake-Java easily integrates with all the latest Java frameworks and platforms like Spring, Maven, log4j, Struts, Kotlin, Grails, Groovy, and many more. Plus, Airbrake-Java allows you to easily customize exception parameters and gives you full, configurable filter capabilities so you only gather the errors that matter most.

Check out all the amazing features Airbrake-Java has to offer and see for yourself why so many of the world’s best engineering teams are using Airbrake to revolutionize their exception handling practices!