try/catch Statement and print out error message - Java Language Basics

Java examples for Language Basics:try catch finally

Introduction

format of try/catch Statement

try {
    body-code
} catch (exception-classname variable-name) {
    handler-code
}

Demo 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());
    }
  }
}

Demo Code


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());
    }
  }
}

Demo Code

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());
    }
  }
}

Related Tutorials