Die folgende Java-Klasse verursacht beim Übersetzen zwei Fehlermeldungen.
import java.io.*; class InputFile { FileInputStream fis; InputFile(String filename) { fis = new FileInputStream(filename); } String getLine() { 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; } }
Das folgende nützliche Java-Programm lädt den Inhalt einer spezifizierten URL und gibt sie aus, bzw. speichert sie in einer Datei.
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 GetURL { 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 (Exception e) { System.err.println(e); System.err.println("Usage: java GetURL[ ]"); } finally { // Always close the streams, no matter what. try { in.close(); out.close(); } catch (Exception e) {} } } }
Probieren Sie dieses Programm z.B. mit
java GetURL "http://www-zv.uni-paderborn.de/Studentenwerk/mensa.htm"
Die Ausnahmebehandlung in diesem Programm ist sehr unspezifisch, da nur Exception-Objekte der allgemeinen Klasse Exception abgefangen und behandelt werden.
Versehen Sie dieses Programm mit einer spezifischeren Ausnahmebehandlung, in dem Sie für möglichst viele der eventuellen Ausnahmen individuelle "throw"- und "catch"-Klauseln vorsehen.