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.
Yes, we can define one try block with multiple catch blocks in Java. Every try should and must be associated with at least one catch block.
If a catch block handles multiple exceptions, you can separate them using a pipe (|) and in this case, exception parameter (ex) is final, so you can't change it. The byte code generated by this feature is smaller and reduce code redundancy.
Java Catch Multiple Exceptions A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block.
Yes you can have multiple catch blocks with try statement. You start with catching specific exceptions and then in the last block you may catch base Exception . Only one of the catch block will handle your exception. You can have try block without a catch block.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With