How to avoid setting variable in a try statement

前端 未结 4 1465
轻奢々
轻奢々 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: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.

提交回复
热议问题