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;
}