尝试并抓住投掷

时间:2015-02-19 11:13:15

标签: java

所以我在代码中遇到了这个问题,我想知道这意味着什么。

Java代码:

public object name(Connection connection) throws SQLException 
{
   try {
        //something
        }

    catch (Exception e) {
        //something
        }
}

所以我的问题是,是否有人知道在下列情况下是否会抛出SQLException并捕获任何其他异常?

5 个答案:

答案 0 :(得分:0)

如果catch块没有抛出SQLException,并且如果try-catch块之外没有任何东西抛出SQLException,那么不,这个实现不会抛出SQLException。

在某些情况下,在签名中声明SQLException仍然有效,例如。如果你想要赋予覆盖此方法的子类,则抛出SQLException的可能性。

答案 1 :(得分:0)

try和catch块允许您覆盖一组程序语句的默认错误行为。如果try块中的任何语句生成错误,程序控制将立即转到catch块,该块包含错误处理语句。

答案 2 :(得分:0)

全部取决于//something

public object name(Connection connection) throws SQLException 
{
   try {
        //something1
        }

    catch (Exception e) {
        //something
        }
    //something2

}

如果//something1是[{1}}的原因,那么它将会被SQLException(//某事物)捕获?

如果catch是[{1}}的原因,那么它将被投放到//something2的来电者

答案 3 :(得分:0)

此:

throws SQLException 

对此没有任何影响:

try {
    //something
}
catch (Exception e) {
    //something
}

这两个结构彼此不了解"。

throws子句声明整个方法可能抛出SQLException,但由于你的try-catch块捕获了所有SQLException,该方法可能不会锻炼该选项。如果您希望传播SQLException,但要抓住并处理其他人,您可以考虑编写

try {
  // something
} catch (SQLException e)  { throw e; }
} catch (Exception e) { /* something */ }

答案 4 :(得分:0)

    public void methodName(Connection connection) throws SQLException {
        try {
            ...
            // This SQLException will be caught by the catch block
            throw new SQLException();
            ...
            // This OtherException will be caught by the catch block
            // as OtherException extends Exception
            throw new OtherException();
            ...
        } catch (Exception e) {
            ...
            // This SQLException will be thrown by the method
            throw new SQLException();
            ...
            // This will cause a compile error as methodName
            // throws SQLException but not OtherException or
            // the more generic Exception
            throw new OtherException();
            ...
        }
    }
相关问题