Appliquer la notion

Cet exercice à pour but de mettre en évidence la notion de spécification des exceptions (throws/throw).

Question

Indiquez les éléments manquants pour spécifier (throws) et lever (throw) les exceptions dans le code ci-dessous.

1
import java.io.IOException;
2
3
public class Main {
4
5
    static class Device {
6
        void method() ______ IOException {
7
            ______ new IOException("Device error");
8
        }
9
    }
10
11
    public static void main(String[] args) _____ IOException {
12
        try {
13
            Device device = new Device();
14
            device.method();
15
            System.out.println("Normal flow");
16
        } catch (IOException e) {
17
            System.out.println(e.getMessage());
18
        }
19
20
    }
21
}

Indice

  • Le mot-clé throws permet de spécifier les types d'exceptions qu'une méthode peut générer.

  • Le mot-clé throw permet de lever explicitement une exception vérifiée ou non vérifiée.

Solution

1
import java.io.IOException;
2
3
public class Main {
4
5
    static class Device {
6
        void method() throws IOException {
7
            throw new IOException("Device error");
8
        }
9
    }
10
11
    public static void main(String[] args) throws IOException {
12
        try {
13
            Device device = new Device();
14
            device.method();
15
            System.out.println("Normal flow");
16
        } catch (IOException e) {
17
            System.out.println(e.getMessage());
18
        }
19
20
    }
21
}
1
C:\>javac Main.java
2
Device error