Java 如何访问try-catch中的变量?

Java 如何访问try-catch中的变量?,java,android,json,Java,Android,Json,我在做类似的事情 JSONArray json = uf.getAllRows(); (int x = 0; x <= json.length(); x++) { JSONObject jo = json.getJSONObject(x); //Eclipse is suggesting that use try-catch here. String name = jo.getString("username"); mainll[x] = new LinearLayout(this);

我在做类似的事情

JSONArray json = uf.getAllRows();
(int x = 0; x <= json.length(); x++) {
JSONObject jo = json.getJSONObject(x); //Eclipse is suggesting that use try-catch here.

String name = jo.getString("username");
mainll[x] = new LinearLayout(this);
mainll[x].setId(x);
mainll[x].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,   LayoutParams.WRAP_CONTENT));
mainll[x].setGravity(Gravity.CENTER);
.
.
.
.
}
谁能告诉我如何解决这个问题吗?

这样做:

JSONObject jo;
try {
    jo = json.getJSONObject(x);
} catch (...) {
    jo = null; // or other error handling
}
把所有东西都包起来

try{
  JSONArray json = uf.getAllRows();
  (int x = 0; x <= json.length(); x++) {
  JSONObject jo = json.getJSONObject(x); //Eclipse is suggesting that use try-catch here.

  String name = jo.getString("username");
  mainll[x] = new LinearLayout(this);
  mainll[x].setId(x);
  mainll[x].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
  mainll[x].setGravity(Gravity.CENTER);
}
catch(Exception e){}
试试看{
JSONArray json=uf.getAllRows();

(int x=0;x一个简单的解决方案是,您可以在try..catch块之外声明变量,以便能够访问它

比如说,

String myVariable = "";

try
{
     .
     .
     .
     myVariable = "Some Assignment"; 
}
catch ( Exception e ) { }

必须将
try/catch
之外的jo变量声明为:

String name;
try{

String name = jo.getString("username");
mainll[x] = new LinearLayout(this);
mainll[x].setId(x);
mainll[x].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,   LayoutParams.WRAP_CONTENT));
mainll[x].setGravity(Gravity.CENTER);
}
catch(Exception ex)
{
 ///
}
JSONArray json=uf.getAllRows();
JSONObject jo=null;
字符串名称=”;

(intx=0;x设置“断点”和“调试”,plz,您将发现。。。
String name;
try{

String name = jo.getString("username");
mainll[x] = new LinearLayout(this);
mainll[x].setId(x);
mainll[x].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,   LayoutParams.WRAP_CONTENT));
mainll[x].setGravity(Gravity.CENTER);
}
catch(Exception ex)
{
 ///
}
JSONArray json = uf.getAllRows();
JSONObject jo = null;
String name = "";

(int x = 0; x <= json.length(); x++) {
   try{
     jo = json.getJSONObject(x); //Eclipse is suggesting that use try-catch here.
   }catch(Exception ex){}

   name = jo.getString("username");
   mainll[x] = new LinearLayout(this);
   mainll[x].setId(x);
   mainll[x].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
   mainll[x].setGravity(Gravity.CENTER);
}