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

Omn*_*ent 9 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

作品:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么?

Bhu*_*ale 15

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

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