繁体   English   中英

在Java中“取消嵌套”我的Try / Catch块

[英]“Un-nesting” my Try/Catch block in Java

在学习和更好地理解Java的过程中,有人告诉我,将代码像下面一样嵌套是一种不好的做法。 我的问题是如何使它执行相同的功能,同时使其更易于阅读。 谢谢!

class Test {
    public static void main(String[] args) {
        try {
            int zero = 0;
            int y = 2/zero;
            try {
                Object s = null;
                System.out.println(s.toString());
            }
            catch(NullPointerException e) {
                System.out.println(e);
            }
        }
        catch(ArithmeticException e) {
            System.out.println(e);
        }
    }
}

例如,您可以通过这样编写来删除一个try

try {
    int zero = 0;
    int y = 2/zero;

    Object s = null;
    System.out.println(s.toString());
} catch(NullPointerException e) {
    System.out.println(e);
} catch(ArithmeticException e) {
    System.out.println(e);
}

这当然更具可读性,但并不一定更好。 这取决于您的用例。

你做不到

try {
    int zero = 0;
    int y = 2/zero;

    Object s = null;
    try {            
        System.out.println(s.toString());
    } catch(NullPointerException e) {
        System.out.println("'s' was null, creating a new 's'");
        s = new Object();
    }
    System.out.println(s.toString());

} catch(ArithmeticException e) {
    System.out.println(e);
}

这完全取决于您要在哪里捕获错误。 如果要在1个catch块中捕获2种不同类型的异常,请使用| 运营商。

try {

}catch(NullPointerException | ArithmeticException e) {

}

如果要2个不同的捕获块,只需添加另一个

try {

}catch(NullPointerException npe) {

}catch(ArithmeticException ae) {

}

对于引发异常或选择引发新异常的方法/实例,必须用try / catch包围。 但这完全取决于您要在哪里捕获错误。 引发异常时,将跳过在引发异常之后的try块中的所有代码,并且触发与该try块连接的catch块

您可以在单个try语句的末尾添加多个catch语句,例如

catch(NullPointerException e) {
            System.out.println(e);
        }

catch(ArithmeticException e) {
        System.out.println(e);
       }

而不是在另一个try / catch中进行try / catch

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM