Not able to use Multi Catch from Java Effectively [duplicate]

流过昼夜 提交于 2019-12-01 04:07:17

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();
} 

The compiler is telling you that

} catch (Exception ex) {

will also catch NumberFormatException exceptions because java.lang.NumberFormatException extends java.lang.IllegalArgumentException, which extends java.lang.RuntimeException, which ultimately extends java.lang.Exception.

The types in multi-catch must be disjoint and java.lang.NumberFormatException is a subclass of java.lang.Exception.

In this case multi-catch is not required because NumberFormatException is derived from Exception. You can simply catch only Exception to get them both. If you need another handling for NumberFormatException than for other exceptions, you must use the example you posted first.

Prashant

you can use

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

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

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

To add on to Mureinik's solution:

If you would like to differentiate the error handling for each of the subclasses you could use instanceof within the catch block something like:

FileNotFoundException is subclass of IOException

catch (IOException e) {
            if (e instanceof FileNotFoundException)
            {
                System.out.println("FileNotFoundException");
            }
            else if(e instanceof IOException)
            {
                System.out.println("IOException");
            }

        }

Exception is the parent class of all exceptions and ideally (Preferred approach - Best Coding Practice), you should never catch Exception unless you are not sure what is going to be thrown at Runtime in try block.

Since, in your code you are doing NumberFormat operation, which is a child class of Exception, you should not catch Exception (unless other 2 methods may throw unchecked exception) and instead, use:

try {
    int Id = Integer.parseInt(idstr);
    TypeInfo tempTypeInfo = getTypeInfo(String.valueOf(Id));\
    updateTotalCount(tempTypeInfo);
} catch (NumberFormatException npe) {
    npe.printStackTrace();
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!