我对 try-catch 有一个小问题。
我的目标是从 try block 中获取 test
和 test2
值,以便稍后使用。
如何处理?
public class MyApplication {
public static void main(String[] args) {
try {
int test = Integer.parseInt("123");
String test2 = "ABCD";
} catch (NumberFormatException ex) {
System.out.print(ex.getMessage());
}
}
}
最佳答案
你写道:
....that I can use it later....
这取决于稍后的含义,如果您的意思是稍后但以相同的方法,则执行以下操作:
public static void main(String[] args) {
String test2 = "";
try {
int test = Integer.parseInt("123");
test2 = "ABCD";
} catch (NumberFormatException ex) {
System.out.print(ex.getMessage());
}
}
然后你可以使用类似的方法
test2.isEmpty()
检查字符串中的内容是否更新为ABCD...
如果你的意思是稍后但在另一个静态方法中,那么就这样做。
public class MyApplication {
static String test2 = "";
public static void main(String[] args) {
try {
int test = Integer.parseInt("123");
test2 = "ABCD";
} catch (NumberFormatException ex) {
System.out.print(ex.getMessage());
}
}
}
关于java - 从 Try-Catch 中获取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44899171/