In java SE 7 or higher a single block of catch
can handle more than one type of exception, for this you must specify the types of exception you want to capture and separate them by a pipe |
, example:
try {
...
}
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
In this case the pipe is not a logical operator but a syntax of the resource.
In previous versions of Java we had to treat the exceptions individually or use a more comprehensive class (Exception
, for example) to capture launches of all possible exceptions, with this feature we can transform, for example:
This code
try {
System.out.println(10 / 0);
} catch (ArithmeticException e) {
System.out.println("Erro: " + e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println("Erro: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Erro: " + e.getMessage());
}
In this
try {
System.out.println(10 / 0);
} catch (ArithmeticException | IllegalArgumentException | ArrayIndexOutOfBoundsException e) {
System.out.println("Erro: " + e.getMessage());
}
OBS: The variable declared in catch
is always final
, that is, we cannot assign any value to it.
Source: Oracle
I can’t answer that, but I would venture to say that it’s just a syntactic ruse, not a operator as
|
or||
. After all, they are not values that are being combined, but types (types even, not representations of types, such as instances ofClass
etc). So that the usual rules of the language for operators do not apply.– mgibsonbr