Java Handling Exceptions.

Java Catching and Handling Exceptions

  • You use the try, catch, and finally blocks — to write an exception handler.
    try, catch, and finally blocks example:
    ...
      public void writeList() {
        PrintWriter out = null;
        try {
          System.out.println("Entering >try statement");
          out = new PrintWriter(new FileWriter("OutFile.txt"));
          for (int i = 0; i < SIZE; i++) {
            out.println("Value at: " + i + " = " + vector.elementAt(i));
          }
        } catch (ArrayIndexOutOfBoundsException e) {
          System.err.println("Caught " +
                  "ArrayIndexOutOfBoundsException: " + e.getMessage());
        } catch (IOException e) {
          System.err.println("Caught IOException: " + e.getMessage());
        } finally {
          if (out != null) {
            System.out.println("Closing PrintWriter");
            out.close();
          } else {
            System.out.println("PrintWriter not open");
          }
        }
      }
    ...
  • Specifying the Exceptions Thrown by a Method (in this case an IOException):
    ...
      public void writeList() throws IOException {
        Vector vector = new Vector();
        PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt"));
        for (int i = 0; i < 10; i++) {
          out.println("Value at: " + i + " = " + vector.elementAt(i));
        }
        out.close();
      }
    ...
  • When you make the methods throws an exception a calling method should handle the exception.
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.