无法有效使用Java的Multi Catch [英] Not able to use Multi Catch from Java Effectively

查看:96
本文介绍了无法有效使用Java的Multi Catch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很想使用Java-1.7的功能。此功能之一是多捕获。当前我有以下代码

I really want to use features from Java-1.7. One of this feature is "Multi-Catch". Currently I have the following code

try {
    int Id = Integer.parseInt(idstr);

    TypeInfo tempTypeInfo = getTypeInfo(String.valueOf(Id));

    updateTotalCount(tempTypeInfo);
} catch (NumberFormatException numExcp) {
    numExcp.printStackTrace();
} catch (Exception exception) {
    exception.printStackTrace();
} 

我想从上面的代码中删除两个catch块,而是使用单个捕获如下:

I want to remove the two catch blocks from the above code, and instead use single catch like below:

try {
    int Id = Integer.parseInt(idstr);

    TypeInfo tempTypeInfo = getTypeInfo(String.valueOf(Id));

    updateTotalCount(tempTypeInfo);
} catch (Exception | NumberFormatException ex) { // --> compile time error
    ex.printStackTrace();
} 

但是上面的代码给出了编译时错误:

But the above code is giving compile time error:


NumberFormatException已被备用
异常捕获。

"NumberFormatException" is already caught by the alternative Exception.

我理解了上面的编译时错误,但是替换了我的第一段代码。

I understood the above compile time error but what is the replace for my first block of code.

推荐答案

NumberFormatException 的子类例外 。说两个 catch 块应该具有相同的行为,就像说您没有对 NumberFormatException 进行任何特殊处理一样,与 Exception 的常规处理相同。在这种情况下,您可以省略其 catch 块,而仅<< c $ c> catch Exception :

NumberFormatException is a subclass of Exception. Saying that both catch blocks should have the same behavior is like saying that you don't have any special treatment for NumberFormatException, just the same general treatment you have for Exception. In that case, you can just omit its catch block and only catch Exception:

try {
    int Id = Integer.parseInt(idstr);

    TypeInfo tempTypeInfo = getTypeInfo(String.valueOf(Id));

    updateTotalCount(tempTypeInfo);
} catch (Exception exception) {
    exception.printStackTrace();
} 

这篇关于无法有效使用Java的Multi Catch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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