如何捕获多个引发类似和异常异常的方法?使用一个处理程序或每个方法与它的处理程序?

时间:2015-07-13 20:32:43

标签: java exception exception-handling try-catch

在main中,我必须按此顺序调用一些方法:

 try {
        instance.method1()
    } catch (SecurityException | IOException e) {
        e.printStackTrace();
    }

// Other methods...

try {
    instance.method2
} catch (XMLStreamException | IOException e) {
    e.printStackTrace();
}

// Other methods...

try {
     instance.method3
} catch (XMLStreamException | IOException e) {
    e.printStackTrace();
}

问题是:最好处理不同try-catch语句中的方法,还是处理一个处理程序中的所有方法,如下所示?

try {
     instance.method1
     instance.method2
     instance.method3
    } catch (XMLStreamException | IOException | SecurityException e) {
        e.printStackTrace();
    }

3 个答案:

答案 0 :(得分:1)

/* Root */
.list-view { background: grey; }
/* First level li's */
.list-view > li { background: red; }
/* First level of ul's */
.list-view > li > ul { background: orange; }
/* Second level of li's */
.list-view > li > ul > li { background: purple; }
/* Second level of li's, first element */
.list-view ul > li:nth-child(1) { background: green; }
/* Second level of li's, all other elements */
.list-view ul > li:nth-child(1n+2) { background: blue; }

一次尝试阻止所有方法。这样您就可以在单独的catch块中处理特定的异常

答案 1 :(得分:0)

这取决于你是否想要独立地继续以前的陈述:

try {
    instance.method1
    instance.method2
    instance.method3
} catch (XMLStreamException | IOException | SecurityException e) {
    e.printStackTrace();
}

当instance.method1失败时,方法2和方法3不会被执行,在单独的情况下会执行所有

答案 2 :(得分:-1)

它并不是真的更好或更糟。除非您正在执行除打印堆栈跟踪之外的其他操作,否则必须根据该错误执行特定操作,然后您需要将其分开。我更喜欢最后一个选项,因为它更具可读性。