Junior
Le bloc finally est-il toujours exécuté dans une construction try-catch?
sobes.tech IA
Réponse de l'IA
Non, pas toujours. finally peut ne pas s'exécuter dans les cas suivants :
- La terminaison de la JVM pendant l'exécution du bloc
tryoucatch. Par exemple, lors de l'appel àSystem.exit(). - Échec de la JVM (par exemple, erreur de mémoire ou débordement de pile).
- Une boucle infinie dans le bloc
tryoucatch. - La terminaison du thread exécutant le bloc
try-catch-finally.
Dans d'autres cas, même si une exception non vérifiée est levée ou si un retour est effectué depuis le bloc try ou catch, le bloc finally sera exécuté.
public class FinallyExample {
public static void main(String[] args) {
try {
System.out.println("Dans le bloc try");
// Sortie de la JVM avant l'exécution de finally
// System.exit(0);
throw new RuntimeException("Exception forcée");
} catch (RuntimeException e) {
System.out.println("Dans le catch : " + e.getMessage());
// Retour depuis catch, finally sera quand même exécuté
// return;
} finally {
System.out.println("Dans le bloc finally"); // Ce code s'exécute
}
System.out.println("Après try-catch-finally"); // Ce code peut ne pas être atteint
}
}