开发者

why does a return statement inside a try catch work with 'throws'

开发者 https://www.devze.com 2022-12-10 12:05 出处:网络
does not work (Compilation error: missing return statement) public SqlMapClientTemplate getSqlTempl() throws UivException, SQLException{

does not work (Compilation error: missing return statement)

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);
    }
}

works:

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 (d开发者_开发知识库sc, scl);
    }
    catch (NamingException ne)
    {
        log.error(ne.getMessage(), ne);
        throw new SQLException("Unable to get database connection: " + ne.getMessage());
    }
}

why?


In first case the method is not returning anything after the catch block or inside the catch block.

In second case the catch block is throwing an exception so compiler know that the method will return an object or throw an exception.


In the first case if the exception is thrown there is no return value, the function just falls off the end, which is an error, same as:

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

In the second the function is guaranteed to return a value or throw an exception.

If you really just want to log the exception, but not take any other action like in the first example you could write something like:

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;
}


As Bhushan mentioned, the compiler can see in this instance that something will always happen there will be a return or an exception. In your first case if you get a Naming Exception you end up in an ambiguous state, nothing returns from a function that contractually has to have a return.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号