Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a Java 7 multicatch block what is the type of the caught exception?

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.

like image 949
Andrew Avatar asked Dec 05 '11 22:12

Andrew


People also ask

What are multi catches in Java 7?

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.

What is the type of error in catch block?

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

What is caught exception in Java?

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 .

What are the types of Java exceptions?

There are mainly two types of exceptions in Java as follows: Checked exception. Unchecked exception.


1 Answers

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.

like image 64
gustafc Avatar answered Sep 21 '22 23:09

gustafc