Ausnahmen werden abgefangen, indem man Programmcode in try-Klauseln einschließt.
try block catch (exception_type id) block catch (exception_type id) block ... finally block
Ausführung
Die Regeln sind eigentlich etwas komplizierter, da die catch- und finally-Blöcke ihrerseits Ausnahmen auslösen können.
Unser Beispiel:
try { attributedObj.replaceValue("Alter", 32); } catch (NoSuchAttrException e) // kann nicht vorkommen. // falls es doch vorkommt, // korrigieren wir es: { Attr a = new Attr(e.attrName, e.newVal); attributedObj.add(a); }
finally ist bisweilen auch ohne Ausnahmebehandlung nützlich:
try { input = new Stream(file); while (!input.eof()) if (input.next() == word) return true; return false; // nicht gefunden } finally { if (input != null) input.close(); }
Der finally-Block wird immer mit einem bestimmten Grund betreten:
Wird finally normal verlassen, bleibt dieser Grund für das gesamte try bestehen.
Wird finally wegen Exception oder return verlassen, bestimmt dies den ``Grund'' der gesamten try-Anweisung.
try { .... return 1; } finally { return 2; }
Gibt 2 zurück. Das wäre sogar so, wenn der try-Block eine Ausnahme ausgelöst hätte.
Noch ein Beispiel:
class TestExcpt extends Exception { TestExcpt() {} TestExcpt(String s) {super(s);} } public class Test { public static void main(String[] a) { for (int i=0; i < a.length; i++) try { werfer(Integer.parseInt(a[i])); System.out.println("no exception"); } catch (Exception e) { System.out.println (e.getClass() + "\n\t" + e.getMessage()); } } static int werfer(int i) throws TestExcpt { switch (i) { case 0: return i/i; case 1: return (new int[-9]).length; case 2: throw new TestExcpt("Test"); } return 0; } }
Dieses Beispiel erzeugt beim Aufruf
java Test 0 1 2 3
die Ausgabe
class java.lang.ArithmeticException / by zero class java.lang.NegativeArraySizeException null class TestExcpt Test no exception