Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct usage of IllegalArgumentException

Original question is here

I am reading in a UTF-8 file and parsing the contents of that file. If there is error in the file there is no point to continue and execution should stop. I have been suggested to throw IllegalArgumentException if there are problems with the contents, but the API doc says:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

In my code, the argument would be the file (or actually the path) that I pass, is it correct to throw IllegalArgumentException in case something goes wrong while parsing? If not, what type of exception should I throw?

private char[][] readMazeFromFile(Path mazeFile) throws IOException {
    if (!Files.isRegularFile(mazeFile) || !Files.isReadable(mazeFile)) {
        throw new IllegalArgumentException("Cannot locate readable file " + mazeFile);
    }
    List<String> stringList = Files.readAllLines(mazeFile, StandardCharsets.UTF_8);
    char[][] charMaze = new char[stringList.size()][];

    for (int i = 0; i < stringList.size(); i++) {
        String line = stringList.get(i);
        if (line.length() != charMaze.length)
            throw new IllegalArgumentException(String.format("Expect the maze to be square, but line %d is not %d characters long", line.length(), charMaze.length));
        if (line.contains("B")) {
            startX = i;
            startY = line.indexOf("B");
        }
        if (line.contains("F")) {
            endX = i;
            endY = line.indexOf("F");
        }
        charMaze[i] = line.toCharArray();
    }

    if (startX == -1 || startY == -1)
        throw new IllegalArgumentException("Could not find starting point (B), aborting.");
    if (endX == -1 || endY == -1)
        throw new IllegalArgumentException("Could not find ending point (F), aborting.");
    return charMaze;
}
like image 263
Erki M. Avatar asked May 22 '14 14:05

Erki M.


People also ask

What is the use of IllegalArgumentException?

The IllegalArgumentException is an unchecked exception in Java that is thrown to indicate an illegal or unsuitable argument passed to a method. It is one of the most common exceptions that occur in Java.

What is IllegalArgumentException in Java with example?

An IllegalArgumentException is thrown in order to indicate that a method has been passed an illegal argument. This exception extends the RuntimeException class and thus, belongs to those exceptions that can be thrown during the operation of the Java Virtual Machine (JVM).

When should you throw IllegalStateException?

The IllegalStateException is thrown when the Java environment or application is not in an appropriate state for the requested operation. This can occur when dealing with threads or the Collections framework of the java. util package under specific conditions.

How do you throw IllegalArgumentException in Java?

public int calculateFactorial(int n) { if (n < 0) throw new IllegalArgumentException("n must be positive"); if (n >= 60) throw new IllegalArgumentException("n must be < 60"); ... } If you know that a parameter to your method cannot be null, then it is best to explicitly check for null and throw a NullPointerException.


1 Answers

I think the first usage is correct:

if (!Files.isRegularFile(mazeFile) || !Files.isReadable(mazeFile)) {
    throw new IllegalArgumentException("Cannot locate readable file "+mazeFile);
}

Since (as the documentation states) an invalid file was provided as the argument, this should throw an IllegalArgumentException. Once you know you have an actual file that meets those requirements, I personally don't think that is a good exception to throw. This will cause other developers to question the type of argument that was given as opposed to the contents of the file. I guess your options are:

  • Keep it as is, just with very specific error messages explaining why this was an invalid argument.

  • Use some other, potentially more applicable java exception such as java.text.ParseException, since it is the file parsing that is causing the error.

  • Create a custom exception class that more sufficiently describes the issue with the file, e.g. a MazeParseException (per the comments) or a FileFormatException.

I would expect the second or third option to be more beneficial if you anticipate several other developers executing your function.

like image 152
Joel Avatar answered Oct 31 '22 17:10

Joel