【问题标题】:How do IDE's "know" when an object needs to be in a try/catch block?IDE 如何“知道”对象何时需要位于 try/catch 块中?
【发布时间】:2015-04-28 06:21:26
【问题描述】:

有时当我使用 Java 编码时,我会忘记将一些代码放入 try/catch 块中。 Eclipse 和 IntelliJ Idea 都警告我将其放入 try catch 块中或使函数抛出异常。

我的问题是,IDE 如何识别我的代码何时需要在 try/catch 中?另外,IDE 如何知道应该抛出什么类型的异常? 例如:

// Bad
private static void makeConnection(){
    Connection con = DriverManager.getConnection("someConnection", "someLogin", "somePassword");
}

// Good
private static void makeConnection() throws SQLException{
    Connection con = DriverManager.getConnection("someConnection", "someLogin", "somePassword");
}

// Also Good
private static void makeConnection(){
    try {
        Connection con = DriverManager.getConnection("someConnection", "someLogin", "somePassword");
    }
    catch(Exception ex){
        System.out.println("Error: " + ex.toString());
    }
}

【问题讨论】:

  • 你认为函数声明中的throws SQLException是什么意思?

标签: java eclipse exception intellij-idea try-catch


【解决方案1】:

注意此方法定义中的检查异常:

private static void makeConnection() throws SQLException

如果您尝试调用 makeConnection() 而不使用 try/catch 或向消费方法添加 throws 声明,您将收到相同的警告。

DriverManager.getConnection() 方法具有相同的 throws 声明。 IDE 只是响应检查的异常声明。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多