何时使用try多抓? [英] When to use try multi catch?

查看:140
本文介绍了何时使用try多抓?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白什么时候使用多个catch。我看到一些帖子,编译时间类型的多catch异常是最接近的超类型的多种异常类型。

I don't understand when to use multi catch. I saw some posts that compile time type of the multi catch exception is the closest super type of multiple exception types.

让我们说有异常类型A,B和他们最接近的超级类型C.

Lets say there are exception type A,B and their closest super type C.

选项1

try{//whatever}
catch(A|B ex){//whatever}

选项2

try{//whatever}
catch(C ex){//whatever}

选项3

try{//whatever}
catch(A ex){//whatever}
catch(B ex){//whatever}

在出现多个异常的情况下,我们应该在哪个理想情况下使用上面的选项?

In which ideal occasions we should use above options when multiple exceptions are thrown?

推荐答案

Oracle文档,值得注意的点对于新的多catch块是:

As per the Oracle documentation , the notable points for the new multi-catch block is :

catch (IOException|SQLException ex) {
   logger.log(ex);
   throw ex;
} 




如果一个catch块处理多个异常类型,那么catch参数是隐式最终。在这个例子中,catch参数ex是final,因此你不能在catch块内给它赋值。通过编译处理多个异常类型的catch块生成的字节码将比编译许多仅处理一个异常类型的catch块小(因此更优越)。处理多个异常类型的catch块在编译器生成的字节码中不会重复;字节码没有异常处理程序的复制。

If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block. Bytecode generated by compiling a catch block that handles multiple exception types will be smaller (and thus superior) than compiling many catch blocks that handle only one exception type each. A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler; the bytecode has no replication of exception handlers.

如果异常可以不同地处理,那么我相信你应该分开捕捉它们。如果异常处理与多个异常相同,那么可以使用多个catch块。

If the exceptions can be handled differently then I believe you should catch them separately . If the Exception handling is same for the multiple exception then you can use the multi-catch block.

try{//whatever}
catch(A ex){//do something specific for A}
catch(B ex){//do something specific for B}

try{//whatever}
catch(C ex){
 //C is superclass of A and B and you are not concerned about the specific type 
 // will catch even other exceptions which are instanceof C
}

try{//whatever}
catch(A|B ex){//do the same thing for both A and B}

这篇关于何时使用try多抓?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆