Java Exception Handling

Java Exception Handling – IllegalArgumentException

Moving right along through our in-depth Java Exception Handling series, today we’ll be digging into java.lang.IllegalArgumentException. The IllegalArgumentException is intended to be used anytime a method is called with any argument(s) that is improper, for whatever reason.

We’ll spend the few minutes of this article exploring the IllegalArgumentException in greater detail by examining where it resides in the Java Exception Hierarchy. We’ll also show some simple example code that will illustrate how you might use IllegalArgumentExceptions in your own Java projects, so let’s get going!

The Technical Rundown

When Should You Use It?

As previously mentioned, the IllegalArgumentException should be thrown when a value is provided to an argument that just doesn’t quite work within the business logic of the application, but isn’t strictly illegal from the perspective of the JVM. For example, here we have a method that accepts an String parameter called title:

If we attempt to call this method while passing a non-String value (such as an int), as seen above, the compiler will catch the issue and prevent us from even executing the application. In this case, the compiler issues an error indicating that int cannot be converted to a String:

Therefore, the only time an IllegalArgumentException is raised is if the method in question was explicitly designed to throw such an error under certain circumstances — situations that the compiler cannot detect are problems, but the author of the code deems improper.

To illustrate how to properly use an IllegalArgumentException, we have a bit of code. The full sample is provided below for easy copy/pasting, after which we’ll dig into the important bits and explore what’s going on:

Outside of our Book and Logging helper classes, all our logic takes place in two methods, Main.generateLibrary() and Main.generateLibraryInvalid(). We start with the working method of the pair:

Nothing too crazy going on here. We create a little library list of Books and output the count, along with the final book we’ve added at the end ("Les Misérables"). Pay special attention to the final page count argument that is passed for the final Book added to the list in these examples (1463 in the case of "Les Misérables"). The output should be just as expected with no thrown exceptions:

The generateLibraryInvalid() method is similar in that we add two books, output the count, then output a third book. However, in this case the third addition is "In Search of Lost Time" by Marcel Proust, a notoriously lengthy book by any measure at around 4215 pages all told:

While that’s very little difference between the logic of these two methods, running this second one results in a thrown IllegalArgumentException, indicating that the page count of our last book exceeds the maximum allowed limit of 4000:

Why is this exception thrown? The stack trace gives some indication, but the real reason is we made a small modification to the Book.setPageCount(Integer) method definition:

Maybe our publisher has a hard limit on the maximum page length we can produce, but for whatever reason, we’ve decided that the most pages a Book can contain is 4000. To confirm this is the case, we ensure that setPageCount(Integer) throws an IllegalArgumentException anytime the passed pageCount argument exceeds that limit.

While this is a simple example, it should illustrate the kind of scenarios in which an IllegalArgumentException should be used and explicitly raised in your own code.

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!