Issue
I'm sorry. I'm sure this has been answered somewhere here before. However, I can't find it.
Essentially, I have a try/catch block where I seem to get a warning or error no matter what I do. catch(IOException e)
results in a "too broad" warning. catch (FileNotFoundException e)
results in errors from code that requires an IOException catch. catch (FileNotFoundException | IOException e)
results in a "types in multi-catch must be disjoint" error. Finally, putting two catch blocks (one for each exception) results in a "'catch' branch identical to 'FileNotFoundException'" warning.
I don't want to edit IntelliJ's warning system as it is useful.
How can I make the try/catch block below work without warnings or errors?
@Override
public void readFile(File inFile) {
try {
FileReader fr = new FileReader(inFile);
BufferedReader br = new BufferedReader(fr);
// get the line with the sizes of the puzzle on it
String sizes = br.readLine();
// find the height of the puzzle
int height = Character.getNumericValue(sizes.charAt(0));
// create a puzzleArr with a height
this.puzzleArr = new char[height][];
// create the char[] array of the puzzle itself
int ct = 0;
String puzzleLine;
// add the puzzle to puzzleArr
while (ct < this.puzzleArr.length) {
puzzleLine = br.readLine().replaceAll("[^a-z]", "");
this.puzzleArr[ct++] = puzzleLine.toCharArray();
}
// create the LinkedList<char[]> of words to find in the puzzle
String line = br.readLine();
while (line != null) {
line = line.toLowerCase().replaceAll("[^a-z]", "");
this.wordList.add(line.toCharArray());
line = br.readLine();
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Solution
You can find the corresponding inspection at Settings > Editor > Inspections > Java > Error Handling > Overly broad 'catch' block
. I would like to note that this inspection was not enabled by default for me.
There are a couple ways to "fix" the warning.
Use Multi-Catch
@Override
public void readFile(File file) {
try {
...
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Modify Inspection
This is probably the preferred option, especially if you want to avoid disabling the inspection completely. From the description of the inspection:
Reports catch blocks which have parameters which are more generic than the exceptions thrown by the corresponding try block.
Use the first checkbox below to have this inspection only warn on the most generic exceptions.
Use the second checkbox below to ignore any exceptions which hide other exceptions, but which may be thrown and thus are technically not overly broad.
The last paragraph is what we're interested in.
Answered By - Slaw Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.