如何摆脱try / catch块的IOException catch上的IntelliJ警告/错误?

问题描述 投票:6回答:2

对不起。我相信之前已在这里得到了回答。但是,我找不到它。

基本上,我有一个try / catch块,无论我做什么,我似乎都会收到警告或错误。 catch(IOException e)导致“过于宽泛”的警告。 catch (FileNotFoundException e)导致需要IOException catch的代码出错。 catch (FileNotFoundException | IOException e)导致“多捕获类型必须是不相交的”错误。最后,放置两个catch块(每个异常一个)导致“'catch'分支与'FileNotFoundException'相同”警告。

我不想编辑IntelliJ的警告系统,因为它很有用。

如何在不发出警告或错误的情况下使try / catch块工作?

@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();
}
}
java intellij-idea file-io try-catch warnings
2个回答
3
投票

您可以在Settings > Editor > Inspections > Java > Error Handling > Overly broad 'catch' block找到相应的检查。我想请注意,默认情况下我没有启用此检查。

有几种方法可以“修复”警告。

Use Multi-Catch

@Override
public void readFile(File file) {

    try {
        ...
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

}

Modify Inspection

这可能是首选方案,特别是如果您想避免完全禁用检查。从检查的描述:

报告捕获具有参数的块,这些参数比相应的try块抛出的异常更通用。

使用下面的第一个复选框让此检查仅警告最常见的异常。

使用下面的第二个复选框忽略任何隐藏其他异常的异常,但这些异常可能会被抛出,因此在技术上不会过于宽泛。

最后一段是我们感兴趣的。

enter image description here


-4
投票

尝试catch (Exception e){}它应该工作

© www.soinside.com 2019 - 2024. All rights reserved.