How to avoid setting variable in a try statement

前端 未结 4 1434
轻奢々
轻奢々 2020-12-22 04:45

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

Later on I need to use that variable but it is now out of scope, or s

相关标签:
4条回答
  • 2020-12-22 05:19

    The way you are declaring the rs variable and the first try/catch block are ok.

    Its just that after the first try/catch you need to remember that rs will still be null if there was an error in the first try/catch. So just make sure you test rs for null before you try to access it.

    0 讨论(0)
  • 2020-12-22 05:21

    Thanks everyone for your help. First you helped me identify that there had to be some kind of exception being thrown. When I looked at the Tomcat console I could see it was a class not fund error for the MySQL connector. I had included that in my project, but not within the project itself - I just lazily referred to it in my lib directory, so ultimately the exception caused the problem, but using your suggestions such as if(rs != null) helped me get to the root cause.

    Initially I thought it had something to do with the variable being out of scope. Clearly that was not it.

    0 讨论(0)
  • 2020-12-22 05:36

    Your problem is that if this statement:

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

    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.

    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.

    0 讨论(0)
  • 2020-12-22 05:39

    Why don't you simply add a

    if(rs != null)
    

    before

    while(rs.next())
    

    This should help (as far as I understand it)

    0 讨论(0)
提交回复
热议问题