How to get a variable from a try / catch block?

I am trying to get this right in 2 days, and I am ready to quit something .....

I have a JSONArray that I am processing in a try / catch block, but it does not seem to pass this variable at the end.

My code is:

try{ //Get the element that holds the results ( JSONArray ) JSONArray getresults = json.getJSONArray("results"); //Loop the Array for(int i=0;i < getresults.length();i++){ HashMap<String, String> map = new HashMap<String, String>(); JSONObject e = getresults.getJSONObject(i); totalpass = e.getJSONObject(i).getString("ftotalpass"); } } catch(JSONException e) { Log.e("log_tag", "Error parsing data "+e.toString()); } 

I tried the whole estate to declare a variable before, after, after the try / catch block, but I just can't get it to go to the rest of my code.

What am I doing wrong?

+6
source share
4 answers

Hm ...

You can declare it outside. For instance,

 JSONArray results = null; try { results = json.getJSONArray("results"); }... 

This way you can access it outside, but be sure to use if to find out if it is null.

If you do not set JSONArray results = null , the compiler will probably whine about not initializing the variable.

Further explanation:

This is due to the area . When you declare inside try, the scope of the variable ends when the attempt completes. When you declare inside an if, when it if ends, the variable can no longer be accessed. This is very useful for temporary variables, where you only use them to compare or improve code reading, memory reuse, etc. (Idk, if that’s even a word). Anyway, if your variable should be accessible everywhere inside the class, it might be better to declare it as a field.

I have not read this explanation , but it seems good. Take a look.

+8
source

Declaring it outside will solve the problem:

 JSONArray getresults = null; try{ //Get the element that holds the results ( JSONArray ) getresults = json.getJSONArray("results"); //Loop the Array for(int i=0;i < getresults.length();i++){ HashMap<String, String> map = new HashMap<String, String>(); JSONObject e = getresults.getJSONObject(i); totalpass = e.getJSONObject(i).getString("ftotalpass"); } } catch(JSONException e) { Log.e("log_tag", "Error parsing data "+e.toString()); } 
+1
source

as Gabriel described the work, but with this approach you may encounter a nullPointerException . I would rather do this:

 JSONArray results = new JSONArray(); try { results = json.getJSONArray("results"); }... 
+1
source

Declare a variable outside the block and assign it inside the block:

 JSONArray getresults; try { ... getresults = ...; // your assignment; ... } catch(JSONException e) { Log.e("log_tag", "Error parsing data" + e.toString()); getresults = ...; //maybe some other assignment } //use variable if(getresults ...) { ... } 
0
source

Source: https://habr.com/ru/post/920222/


All Articles