为什么try catch中的return语句与'throws'一起工作

时间:2009-11-06 02:53:43

标签: java spring

不起作用(编译错误:缺少return语句)

public SqlMapClientTemplate getSqlTempl() throws UivException, SQLException{
    try {
        SqlMapClient scl = (SqlMapClient) ApplicationInitializer.getApplicationContext().getBean("MySqlMapClient");
        DataSource dsc = (DataSource) ServiceLocator.getInstance().getDataSource(PIH_EIV_ORCL);
        return new SqlMapClientTemplate (dsc, scl);
    }
    catch (NamingException ne)
    {
        log.error(ne.getMessage(), ne);
    }
}

工作的:

public SqlMapClientTemplate getSqlTempl() throws UivException, SQLException{
    try {
        SqlMapClient scl = (SqlMapClient) ApplicationInitializer.getApplicationContext().getBean("MySqlMapClient");
        DataSource dsc = (DataSource) ServiceLocator.getInstance().getDataSource(PIH_EIV_ORCL);
        return new SqlMapClientTemplate (dsc, scl);
    }
    catch (NamingException ne)
    {
        log.error(ne.getMessage(), ne);
        throw new SQLException("Unable to get database connection: " + ne.getMessage());
    }
}

为什么?

3 个答案:

答案 0 :(得分:15)

在第一种情况下,该方法不会在catch块之后或catch块内返回任何内容。

在第二种情况下,catch块抛出异常,因此编译器知道该方法将返回一个对象或抛出异常。

答案 1 :(得分:1)

在第一种情况下,如果抛出异常,则没有返回值,即 函数刚刚结束,这是一个错误,同样如下:

public String foo() {
  int x = 5;
}

在第二个功能保证 返回一个值或抛出异常。

如果你真的只是想记录异常,而不是采取任何其他行动 就像在第一个例子中你可以这样写:

public SqlMapClientTemplate getSqlTempl() throws UivException, SQLException{
    SqlMapClientTemplate ret = null; //set a default value in case of error
    try {
        SqlMapClient scl = (SqlMapClient) ApplicationInitializer.getApplicationContext().getBean("MySqlMapClient");
        DataSource dsc = (DataSource) ServiceLocator.getInstance().getDataSource(PIH_EIV_ORCL);
        ret = new SqlMapClientTemplate (dsc, scl);
    }
    catch (NamingException ne)
    {
        log.error(ne.getMessage(), ne);
    }
    return ret;
}

答案 2 :(得分:1)

正如Bhushan所提到的,编译器可以在这种情况下看到一些事情总是会发生,会有返回或异常。在你的第一种情况下,如果你得到一个命名异常,你最终会处于一个模糊的状态,那么从一个合同必须返回的函数中什么也不会返回。