Exemples Java - Utilisation de finally
En Java, le mot-clé finally est généralement utilisé avec try. Une fois que le programme est entré dans le bloc try, peu importe que le programme se termine en raison d'une exception ou qu'il se termine en revenant d'une autre manière, le contenu du bloc finally sera exécuté dans tous les cas.
L'exemple suivant montre comment utiliser finally pour intercepter une exception (exception d'argument illégal) via e.getMessage() :
Fichier ExceptionDemo2.java
public class ExceptionDemo2 {
public static void main(String[] argv) {
new ExceptionDemo2().doTheWork();
}
public void doTheWork() {
Object o = null;
for (int i=0; i<5; i++) {
try {
o = makeObj(i);
}
catch (IllegalArgumentException e) {
System.err.println
("Erreur : ("+ e.getMessage()+").");
return;
}
finally {
System.err.println("Tout a été exécuté");
if (o==null)
System.exit(0);
}
System.out.println(o);
}
}
public Object makeObj(int type)
throws IllegalArgumentException {
if (type == 1)
throw new IllegalArgumentException
("Type non spécifié :" + type);
return new Object();
}
}
La sortie du code ci-dessus est :
都已执行完毕 java.lang.Object@7852e922 Error: (不是指定的类型:1). 都已执行完毕Autres extensions
Exemples Java