P. Pfahler, E. Stümpel

Programmieren in Java, Winter 1997/98

8. Übungsblatt, Lösungsvorschlag


Aufgabe 13 (Ausnahmebehandlung)

Vorgegeben war eine Java-Klasse, die beim Übersetzen die folgenden beiden Fehlermeldungen erzeugte:


InputFile.java:8: Exception java.io.FileNotFoundException must be caught, 
or it must be declared in the throws clause of this method.
                fis = new FileInputStream(filename);
                      ^
InputFile.java:17: Exception java.io.IOException must be caught, 
or it must be declared in the throws clause of this method.
                  c = fis.read();
                                ^
2 errors

Hierzu gab es die folgenden Aufgaben:

Aufgabe 14 (Nochmal Ausnahmebehandlung)

Gegeben war ein Java-Programm, das den Inhalt einer spezifizierten URL liest und sie ausgibt oder in ein Datei schreibt. Da die Ausnahmebehandlung des Programmes sehr unspezifisch gehalten war, sollte es überarbeitet und mit einer besseren Ausnahmebehandlung versehen werden, die für möglichst viele der eventuellen Ausnahmen individuelle "throw"- und "catch"-Klauseln vorsieht.

Ein erster "Trick" um festzustellen, welche spezifischeren Fehlermeldungen durch das allgemeine catch (Exception e) abgefangen werden, ist es, diese "catch"-Klauseln auszukommentieren und sich die Compiler-Fehlermeldungen anzuschauen:


GetURL.java:24: Exception java.net.MalformedURLException must be caught, 
or it must be declared in the throws clause of this method.
      URL url = new URL(args[0]);   // Create the URL
                ^
GetURL.java:25: Exception java.io.IOException must be caught, 
or it must be declared in the throws clause of this method.
      in = url.openStream();        // Open a stream to it
                         ^
2 errors

Noch spezifischere Exceptions, zum Beispiel solche, die zur Klasse der IOExceptions gehören, findet man durch Ausprobieren: Finden möglicher Fehlermeldungen durch Eingabefehler in der URL. Hier einige Beispiele:

java GetURL htpt://
java.net.MalformedURLException: unknown protocol: htpt
Usage: java GetURL  []

java GetURL http://
java.net.ConnectException: Connection refused
Usage: java GetURL  []

java GetURL http://weissnix
java.net.UnknownHostException: weissnix
Usage: java GetURL  []

java GetURL http://www.uni-paderborn.de/weissnix
java.io.FileNotFoundException: http://www.uni-paderborn.de/weissnix
Usage: java GetURL  []

Das um spezifischere Fehlermeldungen erweiterte Programm sieht dann wie folgt aus:

// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples

import java.io.*;
import java.net.*;

/**
 * This simple program uses the URL class and its openStream() method to
 * download the contents of a URL and copy them to a file or to the console.
 **/

public class GetURLnew {
  public static void main(String[] args) {
    InputStream in = null;   
    OutputStream out = null;
    try {
      // Check the arguments
      if ((args.length != 1) && (args.length != 2)) 
        throw new IllegalArgumentException("Wrong number of arguments");

      // Set up the streams
      URL url = new URL(args[0]);   // Create the URL
      in = url.openStream();        // Open a stream to it
      if (args.length == 2)         // Get an appropriate output stream
        out = new FileOutputStream(args[1]);
      else out = System.out;

      // Now copy bytes from the URL to the output stream
      byte[] buffer = new byte[4096];
      int bytes_read;
      while((bytes_read = in.read(buffer)) != -1)
        out.write(buffer, 0, bytes_read);
    }
    // On exceptions, print error message and usage message.

    catch (ConnectException e) {
      System.err.println(e);
      System.err.println("Host not specified or not reachable");
      System.err.println("Usage is:  java GetURL  []");
    }
    catch (UnknownHostException e) {
      System.err.println(e);
      System.err.println("Host doesn't exist!");
      System.err.println("Usage is:  java GetURL  []");
    }
    catch (MalformedURLException e) {
      System.err.println(e);
      System.err.println("Usage is:  java GetURL  []");
    }
    catch (FileNotFoundException e) {
      System.err.println(e);
      System.err.println("File doesn't exist!");
      System.err.println("Usage is:  java GetURL  []");
    }
    catch (IllegalArgumentException e) {
      System.err.println(e);
      System.err.println("1 or 2 Arguments!");
      System.err.println("Usage is:  java GetURL  []");
    }
    catch (IOException e) {
      System.err.println(e);
      System.err.println("Usage is:  java GetURL  []");
    }
    catch (Exception e) {
      System.err.println(e);
      System.err.println("Usage is:  java GetURL  []");
    }
    finally {  // Always close the streams, no matter what.
      try { in.close();  out.close(); } catch (Exception e) {}
    }
  }
}