Handling Exceptions

Contact Us or call 1-877-932-8228
Handling Exceptions

Handling Exceptions

Let's say we are writing a method called getThatInt(ResultSet rs) and we want to use the method getInt(int column) from the ResultSet passed in as a parameter:

public int getThatInt(ResultSet rs) {
	int i = 0;
	return rs.getInt(3);
}

A look at the API listing for ResultSet tells us that the getInt() method throws SQLException, so we must handle that in our code

  1. Use try and catch
    public int getThatInt(ResultSet rs) {
    	int i = 0;
    	try {
    		i = rs.getInt(3);
    	}
    	catch (SQLException e) {
    		System.out.println("Exception occurred!");
    		System.out.println(e.getMessage());
    		e.printStackTrace();
    	}
    	return i;
    }
  2. Declare that the method will throw the exception and let our caller handle it
    public int getThatInt(ResultSet rs) throws SQLException {
    	int i = 0;
    	i = rs.getInt(3);
    	return i;
    }

Note that although you are required to "handle" the exception, you aren't necessarily required to do anything useful about it!

Your decision as to which approach to use should be based on where you think responsibility for handling the exception lies. In the example above, the second approach is probably better, so that the code that works more closely with the SQL handles the exception.

Next