Skip to content
On this page
9. Exceptions
1

Exceptions

15.05.2023
9. Exceptions
2

Exceptions

  • etwas unerwartetes passiert
  • zwei unterschiedliche Typen
    • checked Exceptions: müssen gehandelt werden
    • unchecked Exceptions: dürfen gehandelt werden
  • ... plus Errors
    • z.B. OutOfMemeory
    • ... schwierig bis unmöglich geordnet zu handeln
15.05.2023
9. Exceptions
3

Try / Catch

java
try {
    // probieren
} catch (Exception e) {
    // error handling, falls etwas schiefgeht
} finally { // optional
    // wird immer ausgeführt

}
15.05.2023
9. Exceptions
4

Unchecked Exceptions

java
int[]  values = new int[2];
try {
   int v = values[2];
} catch (Exception e) {
    e.printStackTrace();
}
15.05.2023
9. Exceptions
5

Unchecked Exceptions

Typische Beispiele:

  • NullPointerException
  • IndexOutOfBoundException
15.05.2023
9. Exceptions
6

Unterschiedliche Handler

java
int[]  values = new int[2];
try {
   int v = values[2];
} catch (NullPointerException e) {
    e.printStackTrace();
} catch (IndexOutOfBoundException) {
     e.printStackTrace();
} catch(Exception) { // other
     e.printStackTrace();
}
15.05.2023
9. Exceptions
7

Checked Exceptions

  • Zugriffe auf IO können zu Exceptions führen
    • ... TCP / UDP
    • ... File IO (z.B. FileNotFound)
    • ... UART
  • ... diese müssen gehandelt werden.
15.05.2023
9. Exceptions
8

IOException: Try Catch

java
private void loadFile(String name) {
    try {
        FileReader fr = new FileReader(name);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}
15.05.2023
9. Exceptions
9

IOException: Bubble Up

  • Methode kann via throw forcieren, dass der Methodenaufruf gecheckt werden muss (z.B. mit try/catch oder abermaligem throw):
java
private void loadFile(String name) throws FileNotFoundException {
    FileReader fr = new FileReader(name);
}

public void start() {
    try {
        loadFile("hello.txt");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}
15.05.2023
9. Exceptions
10

Throw

  • Kann das handeln der Exceptions immer weiter "nach oben" delegieren
  • ... bis zur main Methode, oder dem aktuellen Thread
15.05.2023