0

I am using Eclipse Juno, Java and MySQL.

I am just cleaning up my code and would greatly appreciate any advice on the correct way to catch exceptions after reading the database.

When I read my MySQL DB with the following code:

public List<AccountAndCubs> getAccountAndCubs(String AccountId, String user, String pass, String level, String pack, Date archived, String acaId, String cdId, String surname, String firstname) {
    List<AccountAndCubs> accountAndCubsList = new ArrayList<AccountAndCubs>();
    AccountAndCubs accountAndCubs = null; // necessary unless you do something in the exception handler
    accountAndCubsList.clear();
    ResultSet result = null;
    PreparedStatement ps = null;


    try {
      ps = conn.prepareStatement(
      "SELECT at_accounts.*, at_account_cub_association.aca_id," +
              " at_cub_details.cd_id, at_cub_details.cd_surname, at_cub_details.cd_first_name" +
        " FROM at_accounts" + 
        " LEFT JOIN at_account_cub_association ON at_accounts.acc_id = at_account_cub_association.acc_id" +
        " LEFT JOIN at_cub_details ON at_account_cub_association.cd_id = at_cub_details.cd_id" +
        " WHERE (at_accounts.acc_email_address = \"" + user + "\"" + ")" +
        " ORDER BY at_cub_details.cd_surname, at_cub_details.cd_first_name;");

      result = ps.executeQuery();
      while (result.next()) {
          accountAndCubs = new AccountAndCubs(result.getString(1), result.getString(2), result.getString(3), result.getString(4), result.getString(5), result.getDate(6), result.getString(7), result.getString(8), result.getString(9), result.getString(10));
          accountAndCubsList.add(accountAndCubs);
      }
    }
    catch (SQLException e) {
      //do stuff on fail
        System.out.println("SQLException getAccountAndCubs 1.");
        e.printStackTrace();
    }
    finally {
        if (result != null) {
            try {
                result.close();
            }
            catch (SQLException e) {
                System.out.println("SQLException getAccountAndCubs 2.");
                e.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            }   
            catch (SQLException e) {
                System.out.println("SQLException getAccountAndCubs 3.");
                e.printStackTrace();
            }
        }
    }
    return accountAndCubsList;
}

I get the following error in the "Development Mode" panel:

Uncaught exception escaped.
11:47:18.780 [ERROR] [org.AwardTracker.AwardTracker] Uncaught exception escaped

java.lang.NullPointerException: null
at org.AwardTracker.client.AccountUpdateView.renderAccountAndCubsTable(AccountUpdateView.java:444)
at org.AwardTracker.client.AccountUpdateView$GetAccountAndCubsHandler.onSuccess(AccountUpdateView.java:390)
at org.AwardTracker.client.AccountUpdateView$GetAccountAndCubsHandler.onSuccess(AccountUpdateView.java:1)
at com.google.gwt.user.client.rpc.impl.RequestCallbackAdapter.onResponseReceived(RequestCallbackAdapter.java:232)
at com.google.gwt.http.client.Request.fireOnResponseReceived(Request.java:287)
at com.google.gwt.http.client.RequestBuilder$1.onReadyStateChange(RequestBuilder.java:395)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:338)
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:219)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:571)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:279)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:242)
at sun.reflect.GeneratedMethodAccessor24.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:293)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:547)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
at java.lang.Thread.run(Unknown Source)

The result is returned to the client side, as expected, with a row from the "at_accounts" table and no result from the other tables. So no error is resulting on the client side. This is just a clean up so I can write this code correctly and catch the exception before it does become a problem.

Your advice on the correct way to catch exception after reading the database would be greatly appreciated.

Regards,

Glyn

4
  • 5
    Please look at how to use a prepared statement correctly. The current code is vulnerable to SQL injection. Commented Jul 16, 2013 at 2:28
  • 1
    Apparently you're using GWT. It's not clear where the NullPointerException exception is taking place. How are calls made in AccountUpdateView ? Commented Jul 16, 2013 at 2:44
  • Fantastic Paul, this was the next part I was going to clean up. Thank you very much. Commented Jul 17, 2013 at 4:29
  • Hi James, the call is made as follows: syncCallback<List<AccountAndCubs>> callback = new GetAccountAndCubsHandler<List<AccountAndCubs>>(AccountUpdateView.this); rpc.getAccountAndCubs(null, textBoxAccount.getText(), null, null, null, null, null, null, null, null, callback); Commented Jul 17, 2013 at 4:32

3 Answers 3

2

In addition to the comments above you might use the new try-with-resources, it ensures that each resource is closed at the end of the statement thus making your code simpler.

See http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Sign up to request clarification or add additional context in comments.

Comments

1

A NullPointerException almost always indicates an error condition that shouldn't be caught except to be logged or re-thrown (i.e. you shouldn't just ignore the exception). Determine which object is causing the exception, and then determine if it makes sense for the object to be null; if it makes sense for the object to be null then precede the statement throwing the exception with a if(object != null) guard, and if it doesn't make sense for the object to be null then fix the erroneous code that is setting the object to null.

1 Comment

Hi Zim-Zam, I found the error on the client side. I was using != null when I should have been using if (youthMemberList.isEmpty()). Thanks for all your help and the reference material. Regards, Glyn.
1

What you can do is wrap the Exception in a custom-made one suited to higher levels, say DataLayerException. Then rethrow to let it bubble up. Same applies for the service layer (DataLayerException is wrapped in a ServiceLayerException). When the Exception reaches the UI you can intercept it and produce a meaningful message.

Here are some links for reference:

3 Comments

Hi James, This is very helpful and thanks especially for the references. Regards, Glyn.
Happy to help. Did any of the answers posted suit your needs ? If so you should award the user that posted the most relevant answer. Have a nice day.
Hi James, None of these were actually the answer; although they were all very useful. Regards, Glyn.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.