简体   繁体   中英

What exception to throw if JNDI datasource connection is null?

I have following code:

static Connection getConnection() {
        String datasourceContext = "jdbc/infy";
        Connection connection = null;
        try {
            Context initialContext = new InitialContext();

            DataSource datasource = (DataSource) initialContext
                    .lookup(datasourceContext);
            if (datasource != null) {
                connection = datasource.getConnection();
                connection.setAutoCommit(false);
            } else {
                System.out.println("Failed to lookup datasource");
            }
        } catch (NamingException e) {
            System.out.println("Failed to get context " + e);
        } catch (SQLException e) {
            System.out.println("Failed to get connection " + e);
        }
        return connection;
    }

I am trying to make neat and testable code, and my question is: how to correctly handle the case when the datasource is null, or/and connection is null, without using conditional statements. I think the best thing to do is to throw an exception, but what kind of exception? Thank you.

JNDI lookup throws a NameNotFoundException if the datasource is not found. AFAIK it should never return null, so I don't see the point in null check.

You could tweak your error message about NamingException since currently it is misleading, NameNotFoundException is a NamingException as well - though what you really should do is to just rethrow the exception you're getting. I would just change it to unchecked exception instead of checked, like

 catch (NamingException e) {
    throw new IllegalStateException("Failed with JNDI lookup of "
        + datasourceContext, e);
 }

And in the similar way with SQLException.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM