Java examples for Language Basics:try catch finally
format of try/catch Statement
try { body-code } catch (exception-classname variable-name) { handler-code }
import java.io.File; import java.io.IOException; public class Main { public void main() { String filename = "/nosuchdir/myfilename"; try {//from w w w . j a v a2 s . c o m // Create the file new File(filename).createNewFile(); } catch (IOException e) { // Print out the exception that occurred System.out .println("Unable to create " + filename + ": " + e.getMessage()); } } }
import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; public class Main { public void main() { // This URL string is deliberately missing the http: protocol to cause an // exception/*from w w w . j av a 2s. c o m*/ String urlStr = "xeo.com:90/register.jsp?name=joe"; try { // Get the image URL url = new URL(urlStr); InputStream is = url.openStream(); is.close(); } catch (MalformedURLException e) { // Print out the exception that occurred System.out.println("Invalid URL " + urlStr + ": " + e.getMessage()); } catch (IOException e) { // Print out the exception that occurred System.out.println("Unable to execute " + urlStr + ": " + e.getMessage()); } } }
import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; public class Main { public void main() { String urlStr = "httpasdf://xeo.com:90/register.jsp?name=joe"; try {// w ww. ja v a 2s. c o m URL url = new URL(urlStr); InputStream is = url.openStream(); is.close(); } catch (MalformedURLException e) { // Print out the exception that occurred System.out.println("Invalid URL " + urlStr + ": " + e.getMessage()); } catch (IOException e) { // Print out the exception that occurred System.out.println("Unable to execute " + urlStr + ": " + e.getMessage()); } } }