In Java, we will use try-catch
statement to catch and handle the exceptions. More than one exception type can be generated in try
block.
Beginning with Java 7, a new feature called multi-catch has been introduced to allow us to handle multiple exception types with a single catch
block.
In this tutorial, we will show you some examples of how we handle multiple exceptions types in Java 6 and Java 7.
What You’ll Need
- Oracle JDK 1.7 or above
Syntax
This is the syntax of catching multiple exception types in Java 7 or above.
Try {
// Execute statements that may throw exceptions
} catch (ExceptionType1 | ExceptionType2 | ... VariableName) {
// Handle exceptions
}
Java 6 Example
In Java 6 and before, we have to handle multiple exception types with multiple catch
block.
NormalCatchExceptionsExample.java
package com.chankok.exception;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class NormalCatchExceptionsExample {
public static void main(String[] args) {
try {
URL url = new URL("http://www.chankok.com/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
System.out.println("Connecting to www.chankok.com");
System.out.println("Response Code = " + connection.getResponseCode());
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Java 7 Example
Beginning with Java 7, we can handle multiple exception types with a single catch
block. The MalformedURLException
and ProtocolException
are separated by a pipe character |
.
CatchMultipleExceptionsExample.java
package com.chankok.exception;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class CatchMultipleExceptionsExample {
public static void main(String[] args) {
try {
URL url = new URL("http://www.chankok.com/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
System.out.println("Connecting to www.chankok.com");
System.out.println("Response Code = " + connection.getResponseCode());
connection.disconnect();
} catch (MalformedURLException | ProtocolException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}