Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a variable out of a try/catch block?

Tags:

java

android

I've been trying to get this right for 2 days and am about ready to throw something .....

I have a JSONArray which I'm processing in a try/catch block but it doesn't seem to pass the variable out at the end.

My code:

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've tried all manor of declaring the variable before, in, after the try/catch block but I just cannot get it to pass to the rest of my code.

What am I doing wrong?

like image 650
user1517838 Avatar asked Jul 11 '12 13:07

user1517838


1 Answers

Hmm...

You can declare it outside. Such as

JSONArray results = null;

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

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

If you don't put JSONArray results = null the compiler will probably whine about the variable not being initialized.

Further explanation:

This happens because of the scope. When you declare inside the try, the scope of the variable ends when the try ends. When you declare inside an if, when that if ends, the variable can't be accessed anymore. This is very useful for temporary variables where you only use them for comparison or better code readability, memory reuse, etc. (idk if this is even a word). Anyway, if your variable needs to be accessed everywhere inside a class, it may be better to declare as a field.

I didn't read this explanation, but it seems good. Take a look.

like image 99
Comic Sans MS Lover Avatar answered Sep 22 '22 22:09

Comic Sans MS Lover