Correction 13:
Mini-projet 2 (Continuation) + Exceptions


Exercice 1: MOOC (cours en ligne) (MOOC, Niveau 1)

Cet exercice ne nécessite pas de corrigé

Exercice 2: Compile .. ou pas (exceptions, Niveau 1)

Voici une solution possible :

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
class Exemple {
    
    /*Expliquer pourquoi ce code ne compile pas
    SOLUTION : Il faut entourer l'appel de la méthode foo() par un bloc try/catch
    */
    public void m1() {
        foo();
    }
    
    public int foo() throws Exception {
        throw new Exception();
    }
    
    /*Expliquer pourquoi ce code n'est pas considéré comme bon
    SOLUTION : Le premier bloc interceptes les exception de type "Exception",
    donc il intercepte toutes les exceptions possibles. Mais si le code situé
    à l'intérieur du bloc try lève des exceptions précises (NullPointerException,
    IllegalArgumentException, etc...) on perd l'information sur le type d'exception
    qui a été levée.
    */
    public void m2() {
        try {
            //do stuff...
        } catch (Exception e) {
            
        }
    }
    
    /*Expliquer pourquoi ce code ne compile pas
    SOLUTION : Le premier bloc interceptes les exception de type "Exception",
    donc il intercepte toutes les exceptions possibles, y-compris une exception
    de type "NullPointerException". Le deuxième bloc n'est donc jamais atteint.
    */
    public void m3() {
        try {
            //do stuff...
        } catch (Exception e) {
            
        } catch (NullPointerException e) {
            
        }
    }
    
    /*Expliquer pourquoi ce code ne compile pas
    SOLUTION : Il manque "throws CustomCheckedException" à la signature
    de la méthode.
    */
    public void m4() {
        throw new CustomCheckedException();
    }
    
    private class CustomCheckedException extends Exception {
        
        private static final long serialVersionUID = -7944813576443065516L;

        public CustomCheckedException() {
            //nothing
        }
        
    }
    
    /*Expliquer pourquoi ce code ne compile pas
    SOLUTION : La variable "age" n'est pas initialisée. Si le déroulement
    de la méthode "getAccessCode()" ne lance pas d'exception, ce n'est pas un
    problème. Mais dans le cas contraire, la variable "age" ne se verra affecter
    aucune valeur. Il faut donc lui donner une valeur "par défaut".
    */
    public int m5() {
        int age;
        String s = "24";
        try {
            age = getAccessCode();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return age;
    }
    
    public int getAccessCode() throws IllegalAccessException {
        throw new IllegalAccessException();
    }
    
    /*Expliquer pourquoi ce code COMPILE
    SOLUTION : Toutes les exceptions héritant du type RuntimeException ne doivent pas obligatoirement
    être traitées (unchecked exceptions), le compilateur ne signalera ainsi aucune erreur,
    même si l'on n'utilise pas de bloc try-catch. Il n'est pas non plus demandé d'ajouter l'instruction
    "throws RuntimeException" dans la signature de la méthode;
    Exemple de "unchecked exceptions" : 
    NullPointerException, NumberFormatException, IllegalArgumentException, etc...
    */
    public void m6() {
        bar();
    }
    
    public int bar() {
        throw new RuntimeException();
    }
    

}


Exercice 3: Bon projet (exceptions, Niveau 1)

Voici une solution possible :

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
import java.util.Scanner;
import java.util.ArrayList;

class SafeProject {
    
    private final static int NB_PROJECTS = 3;
    
    public static void main(String[] args) {
        ArrayList<Project> projects = new ArrayList<Project>();
        
        do {
            Project project = new Project();
            project.readProject();
            projects.add(project);
        } while (projects.size() < NB_PROJECTS);
    }
}

class Project {
    private String name = null;
    private String subject = null;
    private int duration = -1;

    public Project() {}

    // methode utilitaire utilis'ee par readProject pour la
    // lecture des entiers
    private int readInt(Scanner scanner) throws WrongDurationException {
        String strNumber = scanner.nextLine();
        int number;
        try {
            number = Integer.parseInt(strNumber);
        } catch (NumberFormatException e) {
            throw new WrongDurationException(strNumber + " is not a number !");
        }
        if (number <= 0) {
            throw new WrongDurationException("Duration should be stricly positive !");
        }
        return number;
    }

    // methode utilitaire utilis'ee par readProject pour la
    // lecture des String
    private String readString(Scanner scanner) throws NameTooLongException {
        String str = scanner.nextLine();
        if (str.length() > 50) {
            throw new NameTooLongException("Value should not exceed 50 characters");
        }
        return str;
    }


    // La methode readProject redemande les donn'ees
    // jsuqu'a ce qu'elles soient correctes
    public void readProject() {
        Scanner scanner = new Scanner(System.in);
        do {
            System.out.println("Donnez le nom du projet : ");
            try {
                name = readString(scanner);
            } catch (NameTooLongException e) {
                System.err.println("[ " + e.getMessage() + " ]");
            }
        } while (name == null);

        do {
            try {
                System.out.println("Donnez le sujet du projet : ");
                this.subject = readString(scanner);
            } catch (NameTooLongException e) {
                System.err.println("[ " + e.getMessage() + " ]");
            }
        } while (subject == null);

        do {
            try {
                System.out.println("Donnez la durée du projet : ");
                this.duration = readInt(scanner);
            } catch (WrongDurationException e) {
                System.err.println("[ " + e.getMessage() + " ]");
            }
        } while (duration < 0);
    }
}

class WrongDurationException extends Exception {
    public WrongDurationException(String msg) {
        super(msg);
    }

    public WrongDurationException() {
        super("Wrong duration !");
    }
}

class NameTooLongException extends Exception {
    
    public NameTooLongException(String s) {
        super(s);
    }
    
    public NameTooLongException() {
        super("Too long name !");
    }

}


Exercice 4: Censure (exceptions, Niveau 1)

Cet exercice ne nécessite pas de corrigé.


Exercice 5: Attrapez-les toutes... (exceptions, Niveau 2)

Voici une solution possible :

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import java.util.InputMismatchException;
import java.util.Scanner;

class CustomException extends Exception {

    public CustomException(String string) {
        super(string);
    }

}

final class UtilsMatrix {

    public static int[][] multiply(int[][] mat1, int[][] mat2) throws CustomException {

        checkMatrix(mat1);
        checkMatrix(mat2);

        int rows1 = mat1.length;
        int cols1 = mat1[0].length;
        int rows2 = mat2.length;
        int cols2 = mat2[0].length;     

        if (cols1 != rows2) {
            throw new CustomException("Matrix dimensions must fits");
        }

        int[][] result = new int[rows1][cols2];
        for (int i = 0; i < rows1; i++) {
            for (int j = 0; j < cols2; j++) {
                for (int k = 0; k < rows2; k++) {
                    result[i][j] += mat1[i][k] * mat2[k][j];
                }
            }
        }
        return result;
    }
    
    private static int tryReadInt(Scanner scanner) throws CustomException {
        int val = -1;
        try {
            val = scanner.nextInt();
        } catch (InputMismatchException e) {
            throw new CustomException("Vous devez entrez un nombre");
        }
        if (val <= 0) {
            throw new CustomException("Vous devez entrez des valeurs strictement positives !");
        }
        return val;
        
    }

    public static int[][] readMatrix() throws CustomException {
        Scanner scanner = new Scanner(System.in);
        
        int row = -1;
        int col = -1;

        System.out.println("Nouvelle matrice");
        
        System.out.print("\t Entrez nombre de lignes : ");
        row = tryReadInt(scanner);
        System.out.print("\t Entrez nombre de colonnes : ");

        col = tryReadInt(scanner);
        
        int[][] result = new int[row][col];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                System.out.print("\t Contenu cellule [" + i + "][" + j + "] : ");
                try {
                    result[i][j] = scanner.nextInt();
                } catch (InputMismatchException e) {
                    throw new CustomException("Vous devez entrez un nombre");
                }
            }
        }
        return result;
    }

    /**
     * Ensure that the matrix is not null nor empty and in the right format
     * @param mat
     * @throws CustomException
     */
    public static void checkMatrix(int[][] mat) throws CustomException {
        if (mat == null) {
            throw new CustomException("Matrix should be initialized");
        }
        if (mat.length == 0) {
            throw new CustomException("Matrix should not be empty");
        }
        int lineLength = mat[0].length;
        for (int[] lines : mat) {
            if (lineLength != lines.length){
                throw new CustomException("This is clearly not a matrix !");
            } 
        }
    }
    
    public static void display(int[][] mat) {
        for (int[] lines : mat) {
            for (int item : lines) {
                System.out.print(item + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[][] mat1 = null;
        int[][] mat2 = null;
        boolean dataOk = true;
        do {
            try {
                dataOk = true;
                mat1 = readMatrix();
                mat2 = readMatrix();
            } catch (CustomException e) {
                System.err.println(e.getMessage());
                dataOk = false;
            }
        } while (!dataOk);

        int[][] prod = null;
        try {
            prod = multiply(mat1, mat2);
            display(prod);
        } catch (CustomException e) {
            System.err.println(e.getMessage());
        }
    }
}


Dernière mise à jour: 25/11/2025  (Revision: 1.2)