Java - Try/Catch - 如果成功则访问 try block 中的变量

标签 java try-catch

假设我在某处有以下代码块:

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/

相关文章:

powershell - 捕获错误并重新启动 if 语句

java - GWT 中的客户端时区支持

sql - T-SQL try ... catch 和多个批处理(2 begin...end,if...else)

powershell - 可以使用Write-Error或仅使用throw指定错误类型吗?

try-catch - 如何使用 Haxe 让 FlashDevelop 显示行错误以及错误发生的位置?

javascript - 为什么 catch block 没有触发并且应用程序在 Node.js 中停止工作

java - derby 中的图像数据类型和 BLOB 数据类型

java - ListView 上的 Android 布局充气机不工作

java - Java 中的注解会导致编译时传递依赖吗?

Java EE HTTP 状态 500 - 权限被拒绝