[英]Can we get variable that in Try from catch?
这里只是一个简单的问题。 我们可以获取在Try from catch中声明的变量吗?
例如。
Try {
.....
String s7 = ftpfile1.getName().toString();
.....
}
catch {
System.out.println(s7);
}
我知道这不是获取字符串s7
。 所以,我想问一下,是否有任何可能的方法或我需要做什么来获得捕获中的s7
? 分享的任何例子,相关帖子或答案?
预期结果:可以获得s7
。
感谢您查看,评论和解答。
ps Java新手。
s7
变量的范围就在try{}
块内。 对于变量s7
可以在catch{}
块中使用,您需要增加变量的范围 。 你可以通过在try之外移动声明来做到这一点:
String s7 = null;
try {
.....
s7 = ftpfile1.getName().toString();
.....
} catch (Exception e) {
if (s7 != null) {
System.out.println(s7);
} else {
// s7 is null ...
}
}
您还需要将s7
初始化为某个值,否则编译器会警告您使用未初始化的变量。 这是因为异常会破坏正常的工作流,如果抛出异常,您的变量s7
可能尚未初始化。
在Java中,代码由{
和}
定义的块组织。 在区块内定义的成员无法从外部访问。
{//Block 1
String outside;
{ //Block 2
String value = "in block";
outside = "new Value";
}
}
在上面的例子中,我们有两个集团,我们可以访问内部块中的结构。 我们可以装饰那些块来创建一个类和方法。
class MyClass {
String outside;
void method() {
String value = "in block";
outside = "new Value";
}
}
同样的规则服从try / catch子句。
String s7;
try {
s7 = ftpfile1.getName().toString();
//.....
} catch(Exception e) {
System.out.println(s7);
}
要了解更多信息,请阅读: 块和语句
您可以在try块之前定义变量,然后可以使用catch / finally块访问它
String s7 = null
Try {
.....
s7 = ftpfile1.getName().toString();
.....
}
catch {
System.out.println(s7);
}
只需在try块之前声明你的变量。
String s7 = null;
Try {
s7 = ftpfile1.getName().toString();
}
catch {
System.out.println(s7);
}
你需要在尝试之外的delcare s7。
String s7 = null;
Try {
.....
s7 = ftpfile1.getName().toString();
.....
}
catch {
System.out.println(s7);
}
尝试这样,
String s7 = null;
Try {
.....
s7 = ftpfile1.getName().toString();
.....
}
catch {
System.out.println(s7);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.