我有一个项目,我们经常使用它将Integer.parseInt()String转换为int.当出现问题时(例如,String不是数字而是字母a或其他),此方法将引发异常.但是,如果我必须在我的代码中处理各种异常,那么这很快就会变得非常难看.我想把它放在一个方法中,但是,我不知道如何返回一个干净的值,以表明转换出错了.
在C++中,我可以创建一个接受指向int的指针的方法,让方法本身返回true或false.但是,据我所知,这在Java中是不可能的.我还可以创建一个包含true/false变量和转换值的对象,但这似乎也不理想.对于全局值也是如此,这可能会给我带来一些多线程的麻烦.
那么有一个干净的方法吗?
我有一个非常愚蠢的问题:)
例如,我有以下代码段:
class MyClass {
public static void main (String[] args) {
final String status;
try {
method1();
method2();
method3();
status = "OK";
} catch (Exception e) {
status = "BAD"; // <-- why compiler complains about this line??
}
}
public static void method1() throws Exception {
// ...
}
public static void method2() throws Exception {
// ...
}
public static void method3() throws Exception {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
问题在于:为什么编译器抱怨这一行?
IntelliJ IDEA说,那Variable 'status' might already have …
研究这段代码:
public class TestFinalAndCatch {
private final int i;
TestFinalAndCatch(String[] args) {
try {
i = method1();
} catch (IOException ex) {
i = 0; // error: variable i might already have been assigned
}
}
static int method1() throws IOException {
return 1;
}
}
Run Code Online (Sandbox Code Playgroud)
编译器说 java: variable i might already have been assigned
但对我来说,这似乎是不可能的情况.