Blocs try imbriqués en Java

Mar 04 2023
En Java, une instruction try peut se trouver à l'intérieur du bloc d'un autre try. Il est appelé bloc try imbriqué.

En Java, une instruction try peut se trouver à l'intérieur du bloc d'un autre try. Il est appelé bloc try imbriqué. Chaque fois qu'une instruction try est entrée, le contexte de cette exception est poussé sur la pile.

Pourquoi utiliser un bloc try imbriqué

Parfois, une situation peut survenir où une partie d'un bloc peut provoquer une erreur et le bloc entier lui-même peut provoquer une autre erreur. Dans de tels cas, les gestionnaires d'exceptions doivent être imbriqués.

Syntaxe

try {
   statement 1;
   statement 2;
   try {
      statement 1;
      statement 2;
   }
   catch(Exception e) {
      // catch the corresponding exception  
   }  
}
catch(Exception e) {
   // catch the corresponding exception
}
   .............

// An example of nested try statements.
class NestTry {
public static void main(String args[]) {
    try {
        int a = args.length;
        /* If no command-line args are present,
        the following statement will generate
        a divide-by-zero exception. */
        int b = 42 / a;
        System.out.println("a = " + a);
        try { // nested try block
            /* If one command-line arg is used,
            then a divide-by-zero exception
            will be generated by the following code. */
            if(a==1) a = a/(a-a); // division by zero
            /* If two command-line args are used,
            then generate an out-of-bounds exception. */
            if(a==2) {
                int c[] = { 1 };
                c[42] = 99; // generate an out-of-bounds exception
            }
        } catch(ArrayIndexOutOfBoundsException e) {
        System.out.println("Array index out-of-bounds: " + e);
        }
    } catch(ArithmeticException e) {
    System.out.println("Divide by 0: " + e);
    }
  }
}

Pas de ligne de commande : lorsque vous exécutez le programme sans arguments de ligne de commande, une exception de division par zéro est générée par le bloc try externe.

Un argument de ligne de commande : l'exécution du programme avec un argument de ligne de commande génère une exception de division par zéro à partir du bloc try imbriqué. Étant donné que le bloc interne n'attrape pas cette exception, elle est transmise au bloc try externe, où elle est gérée.

Deux arguments de ligne de commande : si vous exécutez le programme avec deux arguments de ligne de commande, une exception de limite de tableau est générée à partir du bloc try interne. Voici des exemples d'exécutions qui illustrent chaque cas :

C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One
a = 1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One Two
a = 2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42

Ceci est parfois inévitable, surtout si votre code de récupération peut générer une exception. Pas joli, mais parfois il n'y a pas d'alternative.

Notes secondaires

  • Si une instruction try interne n'a pas d' instruction catch correspondante pour une exception particulière, le contrôle est transféré aux gestionnaires catch de l'instruction try suivante qui sont attendus pour une instruction catch correspondante.
  • Cela continue jusqu'à ce que l'une des instructions catch réussisse ou jusqu'à ce que toutes les instructions try imbriquées soient terminées.
  • Si aucune instruction catch ne correspond, le système d'exécution Java gère l'exception. Chaque fois qu'un bloc try n'a pas de gestionnaire catch pour une exception particulière, les blocs catch du bloc try parent sont inspectés pour cette exception, si une correspondance est trouvée pour que ce bloc catch s'exécute. Si ni le bloc catch ni le bloc catch parent ne gère l'exception alors le message généré par le système d'exécution serait affiché pour l'exception, similaire à ce que nous voyons lorsque nous ne gérons pas l'exception.
  • Lorsque des blocs try imbriqués sont utilisés, le bloc try interne est exécuté en premier. Toute exception lancée dans le bloc try interne est interceptée dans le bloc catch correspondant. Si un bloc catch correspondant n'est pas trouvé, alors le bloc catch du bloc try externe est inspecté jusqu'à ce que toutes les instructions try imbriquées soient épuisées. Si aucun bloc correspondant n'est trouvé, l' environnement d'exécution Java gère l'exécution.

// An example of nested try statements.
class NestTry {
public static void main(String args[]) {
try {
  int a = args.length;
  /* If no command-line args are present,
  the following statement will generate
  a divide-by-zero exception. */
  int b = 42 / a;
  System.out.println("a = " + a);
  try { // nested try block
    /* If one command-line arg is used,
    then a divide-by-zero exception
    will be generated by the following code. */
    if(a==1) a = a/(a-a); // division by zero
    /* If two command-line args are used,
    then generate an out-of-bounds exception. */
    if(a==2) {
      int c[] = { 1 };
      c[42] = 99; // generate an out-of-bounds exception
  }
  } catch(ArrayIndexOutOfBoundsException e) {
  System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}

C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One
a = 1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One Two
a = 2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42

/* Try statements can be implicitly nested via
calls to methods. */
class MethNestTry {
static void nesttry(int a) {
  try { // nested try block
    /* If one command-line arg is used,
    then a divide-by-zero exception
    will be generated by the following code. */
    if(a==1) a = a/(a-a); // division by zero
    /* If two command-line args are used,
    then generate an out-of-bounds exception. */
    if(a==2) {
      int c[] = { 1 };
      c[42] = 99; // generate an out-of-bounds exception
  }
  } catch(ArrayIndexOutOfBoundsException e) {
      System.out.println("Array index out-of-bounds: " + e);
  }
}
public static void main(String args[]) {
  try {
    int a = args.length;
    /* If no command-line args are present,
    the following statement will generate
    a divide-by-zero exception. */
    int b = 42 / a;
    System.out.println("a = " + a);
    nesttry(a);
  } catch(ArithmeticException e) {
    System.out.println("Divide by 0: " + e);
  }
}
}

Merci d'avoir lu. Bon apprentissage

Rejoindre Mouad Oumous Java WhatsApp Group REJOINDRE

Rejoindre Mouad Oumous Telegram Channel REJOINDRE

Soutenez notre publication en la suivant