Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to avoid setting variable in a try statement
    text
    copied!<p>My problem is that I have to set a variable in a try statement otherwise I get a compile error.</p> <p>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 <code>NullPointerException</code>.</p> <p>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.</p> <p>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 <code>rs.getString("name")</code> I get the <code>NullPointerException</code>, as this is exactly what I do from the other class (run from a main method for convenience) and it works as expected.</p> <p>The variable in question is the ResultSet variable "rs" -</p> <pre><code>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("&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n" + out.println( "&lt;table border=\"0\" cellspacing=\"0\" cellpadding=\"6\"&gt;\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( " &lt;tr&gt;\n" + " &lt;td&gt;: " + rs.getString("name") + "&lt;/td&gt;\n" + " &lt;/tr&gt;\n" ); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } out.println( "&lt;/table&gt;&lt;/body&gt;\n" + "&lt;/html&gt;" ); out.flush(); out.close(); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload