Partage
  • Partager sur Facebook
  • Partager sur Twitter

utilité du finally bloc try catch

    13 février 2021 à 11:01:14

    bonjour

    je ne comprends pas a quoi sert le bloc finally.

    parce que ces deux blocs fonctionnement de la même facon :

    try {
        Instruction
    } catch(Exception e) {
        e.printStackTrace();
    } finally {
        Instruction
    }

    et

    try {
        Instruction
    } catch(Exception e) {
        e.printStackTrace();
    }
    
    Instruction

    Je trouve le second plus lisible que le premier, mais j'ai des logiciels de revue de code qui me disent qu'il faut un bloc finally


    -
    Edité par TagAda7 13 février 2021 à 11:01:27

    • Partager sur Facebook
    • Partager sur Twitter
      13 février 2021 à 11:20:21

      Salut,

      tu as l'impression que les deux blocs font la même chose car tu catches l'exception pour l'afficher seulement.

      Quand tu as try / finally ou try / catch / finally. Le bloc finally sera appelé même si tu souhaites propager les exceptions.

      Exemple ci-dessous:

          public static void main(String[] args) throws Exception {
              try {
                  method();
              } catch (Exception e){
                  System.err.println(e);
                  throw e;
              } finally {
                  System.out.println("Finally ");
              }
              System.out.println("Suite");
          }
      
          private static void method() throws Exception {
              throw new Exception("BUG");
          }

      ou 

          public static void main(String[] args) throws Exception {
              try {
                  method();
              } finally {
                  System.out.println("Finally ");
              }
              System.out.println("Suite");
          }
      
          private static void method() throws Exception {
              throw new Exception("BUG");
          }




      • Partager sur Facebook
      • Partager sur Twitter

      utilité du finally bloc try catch

      × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
      × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
      • Editeur
      • Markdown