tags:

views:

148

answers:

3

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 (dsc, scl);
    }
    catch (NamingException ne)
    {
        log.error(ne.getMessage(), ne);
        throw new SQLException("Unable to get database connection: " + ne.getMessage());
    }
}

why?

+6  A: 

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.

Bhushan
A: 

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;
}
zimbu668
+1  A: 

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.

Matt
Although, its exactly the same as Bhushan stated, but I liked the way you explained. +1
Adeel Ansari