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 errorsHierzu gab es die folgenden Aufgaben:
import java.io.*; class InputFileCorrect { FileInputStream fis; InputFileCorrect(String filename) { try { fis = new FileInputStream(filename); } catch (FileNotFoundException e) { System.out.println(e+": Datei "+ filename +" nicht gefunden !"); } } String getLine() { int c; StringBuffer buf = new StringBuffer(); try { do { c = fis.read(); if (c == '\n') // UNIX new line return buf.toString(); else if (c == '\r') { // Windows 95/NT new line c = fis.read(); if (c == '\n') return buf.toString(); else { buf.append((char)'\r'); buf.append((char)c); } } else buf.append((char)c); } while (c != -1); } catch (IOException e) { System.out.println(e+": Fehler beim Lesen der Datei!"); } return null; } }
class InputFileTest { public static void main(String argv[]) { InputFileCorrect inf = new InputFileCorrect ("GibtsNicht"); } }Dieses erzeugt zur Laufzeit durch Zugriff auf eine nicht existierende Datei "GibtsNicht" eine java.io.FileNotFoundException :
java InputFileTest java.io.FileNotFoundException: GibtsNicht: Datei GibtsNicht nicht gefunden !
import java.io.*; class InputFileCorrect2 { FileInputStream fis; InputFileCorrect2(String filename) throws FileNotFoundException { fis = new FileInputStream(filename); } String getLine() throws IOException { int c; StringBuffer buf = new StringBuffer(); do { c = fis.read(); if (c == '\n') // UNIX new line return buf.toString(); else if (c == '\r') { // Windows 95/NT new line c = fis.read(); if (c == '\n') return buf.toString(); else { buf.append((char)'\r'); buf.append((char)c); } } else buf.append((char)c); } while (c != -1); return null; } }und Testprogramm2
import java.io.*; class InputFileTest2 { public static void main(String argv[]) { try { InputFileCorrect2 inf = new InputFileCorrect2 ("GibtsNicht"); System.out.println(inf.getLine()); } catch (FileNotFoundException e) { System.out.println(e+": Datei nicht gefunden !"); } catch (IOException e) { System.out.println(e+": Fehler beim Lesen der Datei!"); } } }und man erhält die folgende Ausgabe zur Laufzeit:
java InputFileTest2 java.io.FileNotFoundException: GibtsNicht: Datei nicht gefunden !die sich nicht von der der vorherigen Version unterscheidet. Man erhät also die gleiche Reaktion wie vorher auch.
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 errorsNoch 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 GetURLDas um spezifischere Fehlermeldungen erweiterte Programm sieht dann wie folgt aus:[ ] 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 [ ]
// 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 (Exception e) { System.err.println(e); 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 [ ]"); } [ ]"); } finally { // Always close the streams, no matter what. try { in.close(); out.close(); } catch (Exception e) {} } } }