java - 从 Try-Catch 中获取字符串

标签 java string scope

我对 try-catch 有一个小问题。

我的目标是从 try block 中获取 testtest2 值,以便稍后使用。

如何处理?

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/

相关文章:

java - 调用方法并传递对象引用并使用相同的引用捕获返回

java - 使用 stdin 和 stdout 使用 Java 与外部 C 程序通信

project-management - 如何告诉项目经理 "NO"范围蔓延

c++ - 给定一个 C++ 嵌套私有(private)结构类型,是否有从文件范围静态函数访问它的策略?

c++ - 通过 for 循环对 2D vector 进行 Push_back

Javascript 回调范围问题

java - Android 将图像添加到首选项?

java - Selenium 、Java 和 Angular : Element not interactable

php - 使用php删除字符串中的未知字符

python - 反向字符串:string[::-1] 有效,但 string[0::-1] 和其他无效