RSS feed [root] /design /weblog /exception




login:

password:

title search:




 


Wed Jun 25 01:59:02 GMT 2008

problem of using exception for control flow



Other than harder to read, this approach is easier to have side effect, consider the following case:

// Code which fail
public String service() {
try {
// a lot of other code....
return getRecord();
} catch (SQLException re) {
return "defaultRecord";
}
}

private String getRecord() throws SQLException {
PreparedStatement ps = getConnection().prepareStatement("select something from sometable");
try {
final ResultSet rs = ps.executeQuery();
try {
if (rs.next())
return rs.getString(1);
else
throw new NotFoundException();
} finally {
rs.close();
}
} finally {
ps.close();
}

// definition of NotFoundException, analog to IOException and FileNotFoundException
public final class NotFoundException extends SQLException {....}


The idea is, for any database problem, just return default value. However, if someone change the interface of NotFoundException to

public final class NotFoundException extends RuntimeException {....}

Then it break service() silencely :-/ Some to it is better to have


// Code which fail
public String service() {
try {
// a lot of other code....
return getRecord() == null ? "defaultRecord" : getRecord();
} catch (SQLException re) {
// proper exception handling
}
}

private String getRecord() throws SQLException {
PreparedStatement ps = getConnection().prepareStatement("select something from sometable");
try {
final ResultSet rs = ps.executeQuery();
try {
if (rs.next())
return rs.getString(1);
else
return null;
} finally {
rs.close();
}
} finally {
ps.close();
}




(google search) (amazon search)
second
download zip of files only