Datentypen und Exceptions in Java
Jim White
Java Developer
Exception abfangen und den Fehler behebenthrows an einer Methode die Exception an den Aufrufer zurückgebenthrows eine kommagetrennte Liste von Exception-Typen verwendenpublic static void someMethod() throws IndexOutOfBoundsException,
NegativeArraySizeException, NullPointerException {
// method code
}
Normales try/catch zum Behandeln einer Exception
public static void main(String[] args) {
someMethod();
}
public static void someMethod(){
try {
ArrayList<String> games
= new ArrayList<String>();
games.add("Monopoly");
games.add("Chess");
games.get(3);
} catch (IndexOutOfBoundsException e) {
System.out.println(
"Ups – versucht, ein nicht existentes Element zu holen");
}
}
Throws zum Behandeln einer Exception
public static void main(String[] args) {
try {
someMethod();
} catch (IndexOutOfBoundsException e) {
System.out.println(
"someMethod hat versucht, ein nicht existentes Element zu holen");
}
}
public static void someMethod()
throws IndexOutOfBoundsException {
ArrayList<String> games
= new ArrayList<String>();
games.add("Monopoly");
games.add("Chess");
games.get(3);
}

Exception kann „erneut geworfen" werdenmain zu werfen, beendet die Anwendung
public class RethrowExample {
public static void main(String[] args) {
try {
method1(0);
} catch (ArithmeticException e) {
System.out.println("Oops - tried a bad quotient");
}
}
public static void method1(int divisor) throws ArithmeticException {
method2(divisor);
}
public static void method2 (int divisor) throws ArithmeticException {
int z = 5/divisor;
System.out.println(z);
}
}
Datentypen und Exceptions in Java