The multi-catch
is a language enhancement feature introduces in the Java 7. This allows us to use a single catch
block to handle multiple exceptions. Each exception is separated by the pipe symbol (|
).
Using the multi-catch
simplify our exception handling and also reduce code duplicates in the catch
block. Let’s see an example below:
package org.kodejava.lang;
import java.io.IOException;
import java.sql.SQLException;
public class MultiCatchDemo {
public static void main(String[] args) {
MultiCatchDemo demo = new MultiCatchDemo();
try {
demo.callA();
demo.callB();
demo.callC();
} catch (IOException | SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
}
private void callA() throws IOException {
throw new IOException("IOException");
}
private void callB() throws SQLException {
throw new SQLException("SQLException");
}
private void callC() throws ClassNotFoundException {
throw new ClassNotFoundException("ClassNotFoundException");
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Very simple to implement multi-catch in Java 7 and higher version. Refer https://techgiant.tech.blog/2020/04/15/catching-multiple-exception-types-multi-catch-java-7/