【问题标题】:Correct way to catch an exception in Java after reading a DB读取数据库后在 Java 中捕获异常的正确方法
【发布时间】:2013-07-16 02:23:16
【问题描述】:

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

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

当我使用以下代码读取我的 MySQL 数据库时:

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”表中有一行,其他表没有结果。所以客户端不会产生错误。这只是一个清理工作,因此我可以正确编写此代码并在异常成为问题之前捕获它。

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

问候,

格林

【问题讨论】:

  • 请看how to use a prepared statement correctly。当前代码易受 SQL 注入攻击。
  • 显然您正在使用 GWT。目前尚不清楚 NullPointerException 异常发生在哪里。如何在 AccountUpdateView 中进行调用?
  • 很棒的保罗,这是我要清理的下一部分。非常感谢。
  • 嗨,James,调用如下:syncCallback> callback = new GetAccountAndCubsHandler>(AccountUpdateView.this); rpc.getAccountAndCubs(null, textBoxAccount.getText(), null, null, null, null, null, null, null, null, 回调);

标签: java mysql eclipse


【解决方案1】:

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

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

【讨论】:

  • 谢谢杰拉德,我会试一试的。问候,格林。
【解决方案2】:

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

【讨论】:

  • 您好 Zim-Zam,我在客户端发现了错误。当我应该使用 if (youthMemberList.isEmpty()) 时,我使用了 != null。感谢您的所有帮助和参考资料。问候,格林。
【解决方案3】:

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

以下是一些参考链接:

【讨论】:

  • 嗨詹姆斯,这非常有帮助,特别感谢您的参考。问候,格林。
  • 乐于助人。发布的任何答案是否适合您的需求?如果是这样,您应该奖励发布最相关答案的用户。祝你有美好的一天。
  • 嗨詹姆斯,这些都不是真正的答案;尽管它们都非常有用。问候,格林。
猜你喜欢
  • 2011-05-26
  • 1970-01-01
  • 2012-02-17
  • 2016-12-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多