What is multi-catch in Java, and when is it useful?
Multi-catch is a way of writing one catch block that handles several types of exception at once.
Without it, you have to write one catch block for each type, and if the handling is the same in every one of them, that is a lot of repeated code.
import java.io.IOException;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
try {
readData();
} catch (IOException | SQLException e) {
// One block for both types.
System.out.println("could not read the data : " + e.getMessage());
}
}
static void readData() throws IOException, SQLException {
throw new IOException("the file could not be read");
}
}
It is useful when the types are related enough that you handle them in the same way, and when the types are not related at all and you would otherwise need several nearly identical blocks.
It is not useful when the different types need different handling. Then a separate catch block for each is clearer, because the reader can see at once which failure leads to which response.
The next question in this topic looks at how the caught value behaves.