java - 如何摆脱 try/catch block 的 IOException 捕获上的 IntelliJ 警告/错误?

标签 java intellij-idea file-io try-catch warnings

对不起。我敢肯定这已经在这里的某个地方得到了回答。但是,我找不到它。

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

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

我怎样才能使下面的 try/catch block 在没有警告或错误的情况下工作?

@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();
}
}

最佳答案

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

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

使用多捕获

@Override
public void readFile(File file) {

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

}

修改检查

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

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.

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

enter image description here

关于java - 如何摆脱 try/catch block 的 IOException 捕获上的 IntelliJ 警告/错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54736745/

相关文章:

java - 如何在Java中有效地计算CSV文件的行数

java - 试图解析 json 以在 android 上列出 View 但出现错误

scala - .sc 和 .scala 文件有什么区别?

jquery - 使用 jQuery 插入文件输入元素

java - Android Studio 向导未显示

java - 在 Android 垃圾邮件上旋转屏幕保存的实例状态和 ActivityResultRegistry

java - Maven 多模块项目 - 从另一个模块启动模块?

IDEA Gradle Sync 上的 Java 主目录不同

c - 我如何要求用户提供文件名以用作输入文件?

java - 如何删除写入文件的对象?