catch 块中的 return 语句

问题描述 投票:0回答:3

在用 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(o);”

但是当我添加时输入“return;” 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);
    }
}

它工作完美。
为什么会发生这种情况?
catch 是一个函数吗?
这个return语句指的是什么函数。
预先感谢您!!

java return try-catch
3个回答
2
投票

发生第一个错误是因为如果发生异常,名为

int
o
变量可能无法初始化。在您使用
return
的更新版本中,不会发生此问题:

public static void main(String ...pro) {
    int o;
    try {
        o = 999;
    } catch(Exception mu) {
        System.out.println("sololobo");
        return; // end the call to `main()` here
    }

    // now the following line can only be reached if the try
    // completes without error, which means that o will be defined
    System.out.println(o);
}

2
投票

如果没有

return
,你将永远会到达
System.out.println(o);
语句。编译器不知道
try catch
中的哪个位置发生了错误,因此它不知道
o
是否已正确初始化。

如果你在catch块中返回,那么在任何异常的情况下都不会到达

System.out.println(o);
,这意味着如果代码is到达,则没有异常,这反过来意味着
o
已经被正确设置。


0
投票

伙计们谢谢你们当时的帮助。我是编程新手,我意识到我不知何故“陷入了困惑”。 :D 尊重!

© www.soinside.com 2019 - 2024. All rights reserved.