In a Java 7 multicatch block such as the following:
try { // code that throws exception } catch (CharacterCodingException | UnknownServiceException ex) { // handle exception }
what is the compile-time type of ex
? Is it the most derived class that both exception types have in common? In this example that would be an IOException
.
In Java 7 it was made possible to catch multiple different exceptions in the same catch block. This is also known as multi catch. As you can see, the two exceptions SQLException and IOException are handled in the same way, but you still have to write two individual catch blocks for them.
catch can only handle errors that occur in valid code. Such errors are called “runtime errors” or, sometimes, “exceptions”. That's because the function itself is executed later, when the engine has already left the try...
Each catch block is an exception handler that handles the type of exception indicated by its argument. The argument type, ExceptionType , declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name .
There are mainly two types of exceptions in Java as follows: Checked exception. Unchecked exception.
Yes, the type of ex
is the most specific supertype of both CharacterCodingException
and UnknownServiceException
, which would be IOException
.
Edit: Straight from the horse's mouth on http://cr.openjdk.java.net/~darcy/ProjectCoin/ProjectCoin-Documentation-v0.83.html#multi_catch:
Informally, the lub (least upper bound) is the most specific supertype of the types in question.
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