Wenn eine Ausnahme nicht im Block behandelt wird, wo sie erzeugt wird, propagiert sie in den umfassenden Block, dann in die aufrufenden Methode, usw. bis zur main-Methode.
Wird sie auch dort nicht behandelt, erzeugt der Java-Interpretierer eine Fehlermeldung und beendet die Ausführung.
Beispielprojekt: Fakultätsprogramm
Ziel:
Wir lernen:
Wir brauchen:
Die Fakultätsberechnung
/** fac.java * Implementiert die Fakultätsfunktion * rekursiv. * Arg./Erg.: long (64bit signed integer) * Überprüft Fehler */ public class fac { static final long maxarg = 20; public static long fac (long x) throws IllegalArgumentException { if (x < 0) throw new IllegalArgumentException ("negativ: " + x); if (x > maxarg) throw new IllegalArgumentException ("zu groß: " + x); if ( x == 0) return 1; else return x * fac(x-1); } }
Das Fakultäts-Hauptprogramm
/** facmain.java * Fakultätsprogramm mit * Kommandozeilen-Eingabe */ public class facmain { public static void main (String[] args) { // Versuche, die Fakultät zu berechnen try { int x = Integer.parseInt(args[0]); System.out.println(x + "! = " + fac.fac(x)); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Argument fehlt!");} catch (NumberFormatException e) { System.out.println ("Argument ist keine ganze Zahl!");} catch (IllegalArgumentException e) { System.out.println ("Ungültiges Argument: " + e.getMessage());} } }