java try中的变量

java try中的变量

在Java主函数中,为什么try中的变量不能在try之外被调用

关注:75 答案:4 mip版

解决时间 2021-02-05 22:35

提问者阳光在浪尖跳动

2021-02-05 14:12

public static void main(String[] args){

File file1 = new File("H:\\输入的XML文件.xml");

DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();

try{

DocumentBuilder db=dbf.newDocumentBuilder(); Document doc=db.parse(file1);

Element root=doc.getDocumentElement();

}catch(SAXException se){

//解析过程错误

Exception e=se;

if(se.getException()!=null)

e=se.getException();

e.printStackTrace();

}catch(ParserConfigurationException pe){

//解析器设定错误

pe.printStackTrace();

}catch(IOException ie){

//文件处理错误

ie.printStackTrace();

}

我现在要定义一个String变量root1 : root1=root.getTagName();

但是编译器提示root没有定义啊。我已经在try中定义了root,但是为什么不好使,该怎么办。我对Java不是很熟,知道的解释一下,谢谢了

最佳答案

二级知识专家落日海湾

2021-02-05 15:42

1、在try中声明的变量,相当于一个局部变量,其作用域范围,仅限于try中

2、如果在try之前声明的变量,则可以在try中使用

建议:

int num = 0;

try {

System.out.println(num); // 这里是可以访问到的

int num1 = 5;

} catch(Exception e) {

}

System.out.println(num1); // 这里是访问不到的,因为作用域的限制,num1只能在try里面进行访问。

全部回答

1楼回憶沒有意義

2021-02-05 16:51

try{

捕捉异常

}catch(){

异常执行块

}finally{

不管是否有异常,都要执行的语句块

}

try{

}catch(exception ex){

}

try{

}

主要有这三种使用方法

2楼吃貨一枚

2021-02-05 16:46

try 块是一个小的作用域,在try块中定义的变量都是局部变量,而局部变量只能在局部域中使用,出了这个域则无法调用。

如果你想要在try块的内外均使用同一个变量,需要将变量定义为全局变量,在try块外声明即可

3楼会有一股神秘感

2021-02-05 16:37

改成这样:public static void main(String[] args){

File file1 = new File("H:\\输入的XML文件.xml");

DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();

DocumentBuilder db = null;

Document doc = null;

try{

db =dbf.newDocumentBuilder();

doc =db.parse(file1);

。。。。。。。。

}

我要举报

如以上问答内容为低俗/色情/暴力/不良/侵权的信息,可以点下面链接进行举报,我们会做出相应处理,感谢你的支持!

→点此我要举报以上信息!←

推荐资讯

大家都在看

相关阅读