读取数据库后在Java中捕获异常的正确方法

时间:2013-07-16 02:23:17

标签: java mysql eclipse

我正在使用Eclipse Juno,Java和MySQL。

我只是在清理我的代码,并且非常感谢有关在读取数据库后捕获异常的正确方法的任何建议。

当我使用以下代码阅读MySQL DB时:

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;
}

我在“开发模式”面板中收到以下错误:

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)

结果将按预期返回到客户端,其中包含“at_accounts”表中的一行,而其他表中没有结果。因此,客户端没有出现错误。这只是一个清理,所以我可以正确编写这段代码,并在它成为问题之前捕获异常。

非常感谢您在阅读数据库后获取异常捕获方法的建议。

此致

格林

3 个答案:

答案 0 :(得分:2)

除了上面的注释之外,您还可以使用新的try-with-resources,它确保在语句结束时关闭每个资源,从而使代码更简单。

请参阅http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

答案 1 :(得分:1)

你可以做的是将Exception包装在一个适合更高级别的定制的中,例如DataLayerException。然后重新抛出让它冒出来。同样适用于服务层(DataLayerException包含在ServiceLayerException中)。当异常到达UI时,您可以拦截它并产生有意义的消息。

以下是一些供参考的链接:

答案 2 :(得分:1)

NullPointerException几乎总是表示除了被记录或重新抛出之外不应该被捕获的错误条件(即,您不应该忽略该异常)。确定导致异常的对象,然后确定对象是否有意义为null;如果对象为null是有意义的,那么在使用if(object != null)保护引发异常的语句之前,如果对象为null则没有意义,那么修复设置对象的错误代码为空。