如何避免在try语句中设置变量 [英] How to avoid setting variable in a try statement

查看:108
本文介绍了如何避免在try语句中设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是我必须在try语句中设置一个变量,否则会出现编译错误。

My problem is that I have to set a variable in a try statement otherwise I get a compile error.

稍后我需要使用该变量但它是现在超出​​范围,或者我相信。我在try语句之外初始化变量并将其设置为null,我认为它可以在外面访问,但我仍然得到 NullPointerException

Later on I need to use that variable but it is now out of scope, or so I believe. I initialise the variable outside the try statement and set it to null, I thought that it might then be accessible outside, but I still get a NullPointerException.

代码在下面,大量的代码用于使阅读更容易 - 我知道这是错误的代码,但我是Servlets的新手,只是想看到它运行所有正在运行的部分它们应该是什么。

The code is below, with lots of it taken out to make reading easier - I know it's bad code, but I am new to Servlets and just wanted to see it running with all the moving parts doing what they are supposed to.

我创建了另一个调用createDocs(...)并传入所需参数的类,它工作正常。所以这让我很好奇为什么当我调用 rs.getString(name)我得到 NullPointerException ,这正是我从其他类做的事情(为方便起见,从主方法运行),它按预期工作。

I have created another class that calls createDocs(...) and passes in the required parameters, and it works fine. So that is making me curious as to why when I call rs.getString("name") I get the NullPointerException, as this is exactly what I do from the other class (run from a main method for convenience) and it works as expected.

有问题的变量是ResultSet变量rs -

The variable in question is the ResultSet variable "rs" -

public class AgReportServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public AgReportServlet() {
        super();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ResultSet rs = null;
        try {
            rs = docs.getDocs(con, start, end, zone, locality);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        response.setContentType("text/xml");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" +
                out.println(
                        "<table border=\"0\" cellspacing=\"0\" cellpadding=\"6\">\n");

        // I have a resultset object need to iterate through it to display the file names

        try {
            while (rs.next()) { // page through the result set

                out.println(
                        "  <tr>\n" +
                                "    <td>: " + rs.getString("name") + "</td>\n" +
                                "  </tr>\n"
                );
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        out.println(
                "</table></body>\n" +
                        "</html>"
        );

        out.flush();
        out.close();
    }
}


推荐答案

您的问题是如果这句话:

Your problem is that if this statement:

rs = docs.getDocs(con, start, end, zone, locality);

抛出异常,然后rs的值仍为 null 。所以我要做的是将循环移动到同一个try-catch块中。或者你可以在尝试使用它之前检查它是否仍然为空。

throws an exception then the value of rs is still null. So what I would do is move the loop inside the same try-catch block. Alternatively you can check whether it's still null before trying to use it.

尽管在try-catch块之外将值设置为null也不错。如果你想在try块之外使用rs变量(并且包含在其中一个catch子句中),那就是你必须要做的。你的rs while循环应该只是在同一个try块中。

Setting the value to null outside the try-catch block isn't bad code though. That's just what you have to do if you want the rs variable outside the try block (and that includes inside one of the catch clauses). Your rs while loop should probably just be within the same try block.

这篇关于如何避免在try语句中设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆