Also, der erste Punkt ist die erste Excpetion.
Eine Exception geht so
try {... Anweisungen ...}
catch (Exception e) {...Anweisungen...}
Zum Beispiel. Der Try-Block ist von Geschweiften Klammern umgeben, wie der Catch-Block. Aber halt! der Catch-Block muss direkt auf den Try Block folgen. Innerhalb des Try-Blocks werden anweisungen ausgeführt. Wenn es zu einem abnormalen Fehler, wie geteilt durch null kommt und es entspricht den Bedingungen des Catch-Blocks, werden die Answeisugnen im nachfolgenden Catch-Block ausgeführt
Bei dem ersten:
try {
int i = 7 % 5;
if ((i / (i % 2)) == 2) {
throw new Exception();
}
System.out.println("Ich mag");
} catch (Exception e) {
Steht zur Diskussion wird der Try-Block ausgeführt - weil die Bedigung
if ((i / (i % 2)) == 2) {
erfüllt ist. Da steht ja throw new Exception. Die Antwort lautet nein. Macht macht einen Kommentar da hin
if ((i / (i % 2)) == 2) {
//throw new Exception();
}
wird immer noch "Ich liebe" und das wird ja ausgegeben statt "Ich mag" ausgegeben. Gut, die Variable i enthält den Wert
7%5
Ich habe mal ausprobiert, was
System.out.println(((7 % 5) % 2));
ergibt. Es wird 0 ausgegeben, als kommt 0 raus. 0 darf man für den Rest - Modulo nicht benutzen. Wie bei Geteilt. Deswegen:
if ((i / (i % 2)) == 2) {
löst eine Exception aus. Geteilt durch 0.
Genau beim nächsten ist es anders. Kommentiert man die Zeile aus:
try {
if ((7 % 6 / (7 % 6 % 2)) == 1) {
//throw new Exception();
}
System.out.println("nichts mehr, als");
} catch (Exception u) {
System.out.println("es,");
}
Dann wird vom Programm
david@git:~$ javac Mathematiker.java
david@git:~$ java Mathematiker
0
Ich liebe
nichts mehr, als
wenn
ein Programm
funktioniert.
david@git:~$
Ausgegeben, ohne das david... und so weiter. Schauen wir uns das Ergebnis von
(7 % 6 / (7 % 6 % 2))
an. Es ist:
System.out.println((7 % 6 / (7 % 6 % 2)));
1 - also, stimmt die Bedingung
Es wird throw new Exception(); aufgerufen. für das nächste, was "es" erzeugt.
System.out.println("wenn");
ist ausserhalb der inneren Try-Blocks. es gibt noch einen äusseren, aber da nichts ist, wird keine Exception ausgelöst.
int i = true & false ? 0 : 1;
switch (i) {
case 0:
System.out.println("eine Formel");
case 1:
System.out.println("ein Programm");
default:
throw new Exception();
}
Hier geht es ganz anders. Das kommt nicht über eine Exception
true & false ::= false
per Definition. Mit dem Fragezeichen wird abgefragt, ob die Bedigung true ist, da sie das nicht ist, wird 1 ausgewählt.
Es kommt zum switch-case. Es kommt :
case 1:
System.out.println("ein Programm");
Und das default auch. Es wird eine Exception ausgelöst
Im nächsten Try-Block wird noch geprüft eine Arithmetische - das ist eine bestimmte Art aller Exceptions oder irgendeine. Da eine globale ausgelöst wird und keine arithmetische, wird
} catch (Exception e) {
System.out.println("funktioniert.");
ausgelöst.