try catch 后局部变量无法引用到

J2EE 码拜 9年前 (2015-07-18) 1094次浏览

public  void  test  (){
String result;
try {
result = JsonUtils.object2Json(map);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println(result);

}
为啥红色的result引用不到了呢

#1

因为是在result里赋值的,解决方法是
catch以后扔个RuntimeException
Object obj;
try{
obj=new Object();
}catch(NullPointerException e){
throw new RuntimeException(e);
}
System.out.println(obj.toString());//不报错
10分

#2

public  void  test  (){
String result;    //改为String result = null;
try {
result = JsonUtils.object2Json(map);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println(result);

}

#3

什么叫引用不到,你这最多是报变量未初始化错误,在result定义后面赋初值:
String result = null;
就OK了

#4

应该可以用用到的。可能需要初始化

#5

回复3楼:

这样初始化有问题的,有的时候赋值就是在try里,如果try里执行不到,那你即使一开始给了个null让编译通过,执行起来也是有问题的。

#6

String result=””;   //空字符串
10分

#7

回复楼:

你引用了未初始化的变量!

#8

回复6楼:

此贴可取,初始化变量result为空串即可。
可以结贴了
智庵的博客


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明try catch 后局部变量无法引用到
喜欢 (0)
[1034331897@qq.com]
分享 (0)