Appearance
Kapitel 15: Ausnahmebehandlung (Exception Handling)
🎯 Lernziele
- Was sind Exceptions?
try...catch...finally- Häufige Exception-Typen
throwsundthrow- Eigene Exceptions (Einstieg)
15.1 Was sind Exceptions?
🚨 Was passiert bei Fehlern?
Ohne Exception-Handling:
java
public class OhneHandling {
public static void main(String[] args) {
int a = 10;
int b = 0;
System.out.println(a / b); // ❌ Fehler! Programm stürzt ab!
}
}Ausgabe:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at OhneHandling.main(OhneHandling.java:5)→ Programm stürzt ab!
✅ Mit Exception-Handling:
java
public class MitHandling {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
System.out.println(a / b);
} catch (ArithmeticException e) {
System.out.println("Fehler: Division durch Null!");
} finally {
System.out.println("Dieser Block wird immer ausgeführt!");
}
}
}Ausgabe:
Fehler: Division durch Null!
Dieser Block wird immer ausgeführt!→ Programm läuft weiter!
15.2 try...catch...finally
📝 Syntax
java
try {
// Code, der Fehler verursachen könnte
} catch (ExceptionTyp e) {
// Fehlerbehandlung
} finally {
// Wird immer ausgeführt (Ressourcen freigeben!)
}📋 Beispiel 1: ArithmeticException abfangen
java
public class TryCatchBeispiel1 {
public static void main(String[] args) {
try {
int ergebnis = 10 / 0; // Fehler!
System.out.println(ergebnis); // Wird nicht erreicht
} catch (ArithmeticException e) {
System.out.println("Fehler: " + e.getMessage());
}
}
}Ausgabe:
Fehler: / by zero📋 Beispiel 2: ArrayIndexOutOfBoundsException
java
public class TryCatchBeispiel2 {
public static void main(String[] args) {
int[] zahlen = {1, 2, 3};
try {
System.out.println(zahlen[5]); // Fehler! Index 5 existiert nicht
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Fehler: Index außerhalb des Bereichs!");
}
}
}📋 Beispiel 3: finally Block
java
public class FinallyBeispiel {
public static void main(String[] args) {
try {
int[] zahlen = null;
System.out.println(zahlen.length); // NullPointerException
} catch (NullPointerException e) {
System.out.println("Fehler: Nullzeiger!");
} finally {
System.out.println("Finally Block: Wird immer ausgeführt!");
}
System.out.println("Programm beendet.");
}
}Ausgabe:
Fehler: Nullzeiger!
Finally Block: Wird immer ausgeführt!
Programm beendet.15.3 Häufige Exception-Typen
| Exception-Typ | Beschreibung | Beispiel |
|---|---|---|
ArithmeticException | Mathematischer Fehler | 10 / 0 |
ArrayIndexOutOfBoundsException | Array-Index ungültig | array[10] (nur 5 Elemente) |
NullPointerException | Zugriff auf null-Referenz | String s = null; s.length(); |
NumberFormatException | Ungültiges Zahlenformat | Integer.parseInt("abc") |
FileNotFoundException | Datei nicht gefunden | new FileReader("test.txt") |
📋 Beispiel: NumberFormatException
java
public class NumberFormatBeispiel {
public static void main(String[] args) {
try {
int zahl = Integer.parseInt("123a"); // Fehler!
System.out.println(zahl);
} catch (NumberFormatException e) {
System.out.println("Fehler: Ungültiges Zahlenformat!");
}
}
}15.4 throws und throw
📤 throws (Deklaration)
throws = Methode gibt Exception weiter (muss vom Aufrufer behandelt werden).
java
import java.io.FileReader;
import java.io.FileNotFoundException;
public class ThrowsBeispiel {
// Methode gibt Exception weiter
static void dateiLesen() throws FileNotFoundException {
FileReader reader = new FileReader("test.txt"); // Kann Exception werfen
}
public static void main(String[] args) {
try {
dateiLesen();
} catch (FileNotFoundException e) {
System.out.println("Datei nicht gefunden!");
}
}
}🎯 throw (Manuelles Werfen)
throw = Manuelles Auslösen einer Exception.
java
public class ThrowBeispiel {
static void alterPrüfen(int alter) {
if (alter < 0) {
throw new IllegalArgumentException("Alter kann nicht negativ sein!");
}
System.out.println("Alter: " + alter);
}
public static void main(String[] args) {
alterPrüfen(-5); // Fehler!
}
}Ausgabe:
Exception in thread "main" java.lang.IllegalArgumentException: Alter kann nicht negativ sein!15.5 Eigene Exceptions (Einstieg)
🏗️ Eigene Exception-Klasse erstellen
java
// Eigene Exception-Klasse
class MeineException extends Exception {
public MeineException(String nachricht) {
super(nachricht);
}
}
public class EigeneExceptionBeispiel {
static void prüfen(int wert) throws MeineException {
if (wert < 0) {
throw new MeineException("Wert darf nicht negativ sein!");
}
System.out.println("Wert: " + wert);
}
public static void main(String[] args) {
try {
prüfen(-10);
} catch (MeineException e) {
System.out.println("Fehler: " + e.getMessage());
}
}
}📝 Zusammenfassung
In diesem Kapitel hast du gelernt:
- ✅ Exceptions sind Fehler zur Laufzeit
- ✅
try...catch...finallyzum Abfangen von Fehlern - ✅ Häufige Exception-Typen (
ArithmeticException,NullPointerException, etc.) - ✅
throws(Exception weitergeben) undthrow(manuell werfen) - ✅ Eigene Exceptions erstellen
💡 Merksatz für Anfänger
"Nutze
try-catch, um Programmabstürze zu vermeiden!finallywird immer ausgeführt (Ressourcen freigeben)!"
🎯 Nächste Schritte
Im nächsten Kapitel lernst du:
- Häufige Hilfsklassen (Kapitel 16)
Random(Zufallszahlen)Math(Mathematische Funktionen)Date/SimpleDateFormat(Datum)Scanner(Tastatureingabe)
Bereit für Hilfsklassen? Los geht's! 🚀
📚 Weiterführende Links:
💬 Fragen?
Hinterlassen Sie einen Kommentar!
