不起作用(编译错误:缺少返回语句)
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());
}
}
为什么?
最佳答案
在第一种情况下,该方法在 catch block 之后或 catch block 内不返回任何内容。
在第二种情况下,catch block 抛出异常,因此编译器知道该方法将返回一个对象或抛出异常。
关于java - 为什么 try catch 中的 return 语句与 'throws' 一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1685120/