Java Keyword: catch
catch
is used to catch exceptions thrown in a preceeding try
block:
try {
// code that may throw exceptions
} catch (SomeException ex) {
// handle exception
}
There can be multiple catch
blocks after each try
block:
try {
// code that may throw exceptions
} catch (IOException ex) {
// handle IOException
} catch (InterruptedException ex) {
// handle InterruptedException
} catch (Exception ex) {
// handle all other types of exceptions
}
A single catch block can also handle multiple types of exceptions. This is called multicatch and was introduced in Java 7.
try {
// code that may throw exceptions
} catch (IOException | InterruptedException ex) {
// handle IOExceptions and InterruptedExceptions
} catch (Exception ex) {
// handle all other types of exceptions
}
See Java Exceptions: Throw, Try and Catch for details on semantics.
Comments
Be the first to comment!