Correct usage of IllegalArgumentException
exception, illegalargumentexception, java
Solution
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.
Problem
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; } ```