Les exceptions |
Lorsqu'une erreur est detectee, Java lance une exception (throw). Un programme peut egalement explicitement lancer une exception. Une exception est un objet defini par la classe throwable (ou a partir de cette classe).
Un programme lancant une commande peut essayer de la lancer (try) en interceptant (catch) les interruptions. Certaines methodes ne peuvent pas etre lancees sans essayer d'intercepter d'eventuelles interruptions (refus a la compilation).
Si on desire ajouter une partie de code qui soit executee quelle que soit le resultat d'une instruction dans un try {}, on peut ajouter un bloc finally { actions ; }.
Programme :
| public class except
{
static ma_class mon_obj ; public static void main(String[] args) {
try { valeur[5] = 0 ; } catch (Exception e) { System.out.println("5 est en dehors des bornes 0..4 : " + e.getClass() + " " + e.getMessage()) ; } finally { valeur[4] = 0 ; } mon_obj = null ; try { mon_obj.travaille() ; } catch (Exception e) { System.out.println("mon_obj pointe sur null : " + e.getClass() + " " + e.getMessage()) ; } class ma_class {
{ System.out.println("Un objet ma_class travaille") ; } |
Resultat de l'execution :
| 5 est en dehors des bornes 0..4 : class java.lang.ArrayIndexOutOfBoundsException
5
mon_obj pointe sur null : class java.lang.NullPointerException null |
| public class except2
{
static int lance_exception(String s) throws Mes_exceptions {
public static void main(String[] args) {
try {
System.out.println("exception_automatique n'a pas genere d'exception.") ; catch (Exception e) { System.out.println("exception_automatique a genere : " + e.getClass()) ; e.printStackTrace() ; }
{
System.out.println("mon_exception n'a pas genere d'exception.") ;
{ System.out.println("mon_exception a genere : " + e.getClass()) ; e.printStackTrace() ; }
class Mes_exceptions extends Exception {
} |
| Je sorts de lance_exception.
exception_automatique a genere : class java.lang.ArithmeticException java.lang.ArithmeticException: / by zero
Je sorts de lance_exception. mon_exception a genere : class Mes_exceptions Mes_exceptions: mon_exception
at except2.main(except2.java:34) |
| fillInStackTrace() Fills in the execution stack
trace.
getLocalizedMessage() Creates a localized description of this Throwable. getMessage() Returns the detail message of this throwable object. printStackTrace() Prints this Throwable and its backtrace to the standard error stream. printStackTrace(PrintStream) Prints this Throwable and its backtrace to the specified print stream. printStackTrace(PrintWriter) Prints this Throwable and its backtrace to the specified print writer. toString() Returns a short description of this throwable object. |