我运行了这段代码:
public static void main(String[] args) {
System.out.println(catcher());
}
private static int catcher() {
try {
System.out.println("TRY");
thrower();
return 1;
} catch (Exception e) {
System.out.println("CATCH");
return 2;
} finally {
System.out.println("FINALLY");
return 3;
}
}
private static void thrower() {
throw new RuntimeException();
}
我希望看到输出结果如下:
TRY
CATCH
FINALLY
2
但是出乎意料的是,输出结果为:
TRY
CATCH
FINALLY
3
我有些疑惑。 return 2
这个语句该放在哪里?finally
中使用 return
是一种不好的编程习惯吗?
finally
块总是会被调用(如果没有发生崩溃)。 - Marounfinally
块中找到return
。就这样。 - Marko Topolnik