当对象需要在 try/catch 块中时,IDE 的 "know" 怎么办?

How do IDE's "know" when an object needs to be in a try/catch block?

有时当我在 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());
    }
}

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

private static void makeConnection() throws SQLException

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

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