【问题标题】:Using FindBugs in eclipse在 Eclipse 中使用 FindBugs
【发布时间】:2016-02-15 22:48:26
【问题描述】:

我一直在 Eclipse 中使用 Find Bugs,但我无法弄清楚为什么会出现一些错误或如何修复它们。任何想法或帮助都会很棒!

第一个错误是(错误:当banking.primitive.core.ServerSolution.saveAccounts()中没有抛出异常时捕获异常):

} catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();

第二个bug是(Bug:当banking.primitive.core.ServerSolution.saveAccounts()中没有抛出异常时会捕获异常):

out.writeObject(accountMap.get(i));

我尝试将其更改为:

out.writeObject(accountMap.get(Integer.toString(i)));

第三个错误是(Bug:当banking.primitive.core.ServerSolution.saveAccounts()中没有抛出异常时捕获异常):

        } catch (Exception e) {
        e.printStackTrace();
        throw new IOException("Could not write file:" + fileName);

对于第一个错误,我的 try 块也是如此。我搞不清楚了。我试图在下面关注你的帖子,但我很困惑。对不起,我是新手!

    public ServerSolution() {
    accountMap = new HashMap<String,Account>();
    File file = new File(fileName);
    ObjectInputStream in = null;
    try {
        if (file.exists()) {
            System.out.println("Reading from file " + fileName + "...");
            in = new ObjectInputStream(new FileInputStream(file));

            Integer sizeI = (Integer) in.readObject();
            int size = sizeI.intValue();
            for (int i=0; i < size; i++) {
                Account acc = (Account) in.readObject();

                //CST316 TASK 1 CHECKSTYLE FIX
                if (acc != null) {
                    accountMap.put(acc.getName(), acc);
                }
            }
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }
}

【问题讨论】:

  • try 块中调用的方法会抛出哪些已检查异常?抓住那些专门。如果你愿意,也可以抓住RuntimeException

标签: java eclipse findbugs


【解决方案1】:

FindBugs Bug Description:

这个方法使用了一个try-catch块来捕获Exception对象,但是在try块内不会抛出Exception,并且没有显式地捕获RuntimeException。说 try { ... } catch (Exception e) { something } 是一种常见的错误模式,它是捕获多种异常类型的简写,每个异常的 catch 块都是相同的,但是这个结构也意外地捕获了 RuntimeException ,掩盖潜在的错误。

更好的方法是要么显式地捕获特定抛出的异常,要么显式地捕获 RuntimeException 异常,重新抛出它,然后捕获所有非运行时异常,如下所示:

try {
    ...
} catch (RuntimeException e) {
    throw e;
} catch (Exception e) {
    ... deal with all non-runtime exceptions ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多