catch块中的return语句

时间:2016-12-31 10:05:04

标签: java return try-catch

在java中进行编码时,我发现了一件奇怪的事情。

代码以这种方式编写。

class lara {
    public static void main(String ...pro) {
        int o;
        try{
            o=999;
        }catch(Exception mu) {
         System.out.println("sololobo");
        }
    System.out.println(o);
}
}

它会在要求打印o的行显示错误

“的System.out.println(○);”

但是当我添加类型“返回”时catch块内的语句如

class lara {
    public static void main(String ...pro) {
        int o;
        try{
            o=999;
        }catch(Exception mu){
            System.out.println("sololobo");
            return;
        }
    System.out.println(o);
    }
}

效果很好。
为什么会发生这种情况?
是抓住一个功能吗? 这个return语句指的是什么函数。
谢谢你提前!!

2 个答案:

答案 0 :(得分:1)

发生了第一个错误,因为如果发生异常,可能无法初始化名为int的{​​{1}}变量。在使用o的更新版本中,不会发生此问题:

return

答案 1 :(得分:1)

如果没有return,您将始终获得System.out.println(o);声明。编译器不知道错误发生在try catch的哪个位置,因此它不知道是否已正确初始化o

如果你在catch块中返回,如果有任何异常,将无法访问System.out.println(o);,这意味着如果 到达,那么也不例外,这反过来意味着o已被正确设置。

相关问题