Skip to content

Instantly share code, notes, and snippets.

@chankok
Last active January 15, 2017 14:53
Show Gist options
  • Save chankok/c3fda1d6fc5cffa71fb3c965fbb011ab to your computer and use it in GitHub Desktop.
Save chankok/c3fda1d6fc5cffa71fb3c965fbb011ab to your computer and use it in GitHub Desktop.
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