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

7

9

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

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" 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.

Gewgaw answered 2/9, 2015 at 5:33 Comment(0)
D
12

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();
} 
Dowling answered 2/9, 2015 at 5:36 Comment(0)
T
3

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.

Tennes answered 2/9, 2015 at 5:37 Comment(0)
M
2

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

Mori answered 2/9, 2015 at 5:37 Comment(0)
D
2

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

        }
Deerstalker answered 15/11, 2016 at 6:1 Comment(1)
You can directly use multiple catch blocks to catch different types of exceptions in order of specific to general instead of using an instanceof for each type of exception.Haiphong
T
1

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.

Telegraphese answered 2/9, 2015 at 5:37 Comment(0)
S
1

you can use

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

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

    updateTotalCount(tempTypeInfo);
  } catch (Exception exception) {
    exception.printStackTrace();
  } 
Shinleaf answered 2/9, 2015 at 5:37 Comment(2)
Thanks for the edits @Am_I_Helpful. In spirit of the edit you made, You_are_helpful :)Shinleaf
Thanks for acknowledging me with "You_are_helpful"! Thanks again. And a +1Amboise
H
0

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();
} 
Hullabaloo answered 2/9, 2015 at 5:48 Comment(2)
Thank you @stategroup, I know that the Exception is super class , but i don't know other type of exceptions at run time, thats why my code has NumberFormatexception(expected) and excetpion(unexpected).Gewgaw
@M.S.Naidu, To ensure that your code won't throw any other exception, you can check other methods that you are calling. If you are not doing any IO operations, class cast, etc. (that might throw RunTime exception) then you don't need to catch Exception. The reason Java has different exception level is so that you can have fine control over your code. This way, you can catch an exception and choose to ignore it or re-throw itHullabaloo

© 2022 - 2024 — McMap. All rights reserved.