In java SE 7 or higher a single block of catch
can deal with more than one type of exception, for this you must specify the types of exception you want to capture and separate them with 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 feature syntax.
In previous versions of Java we had to treat exceptions individually or use a more comprehensive class ( Exception
, for example) to capture postings 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());
}
NOTE: The variable declared in catch
is always final
, ie we can not assign any value to it.
Source: Oracle