Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java Example: Catch Multiple Exceptions http://www.chankok.com/java-catch-multiple-exceptions/
// Syntax of catching multiple exceptions
Try {
// Execute statements that may throw exceptions
} catch (ExceptionType1 | ExceptionType2 | ... VariableName) {
// Handle exceptions
}
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();
}
}
}
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();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment