假设我在某处有以下代码块:
while(condition){
try {
String twoStr= JOptionPane.showInputDialog("Enter two words sep by a space.");
\\do stuff like splitting and taking an index which may cause out of bound exception
catch (IOException e) {
System.out.println("Sorry your words are terrible.");
}
\\do stuff with twoStr
我无法访问 try/catch 语句之外的字符串,但我不想提示用户输入另外两个单词,以防他搞砸并输入一个单词。如何访问在 try block 中初始化的这个值?
最佳答案
字符串应该在 try/catch 语句之外定义:
while(condition){
String twoStr = null;
try {
twoStr= JOptionPane.showInputDialog("Enter two words sep by a space.");
} catch (IOException e) {
System.out.println("Sorry your words are terrible.");
}
//do stuff with twoStr
这样,try/catch 语句以及其外部的代码都会看到该变量。您应该阅读scopes以便更好地理解这一点。
关于Java - Try/Catch - 如果成功则访问 try block 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19020300/