Tratarea excepțiilor: Diferență între versiuni

De la WikiLabs
(Generarea excepțiilor)
(Administrarea excepțiilor)
Linia 129: Linia 129:
  
 
=== Administrarea excepțiilor ===
 
=== Administrarea excepțiilor ===
 +
 +
Administrarea unei excepții de face într-un bloc '''try-catch'''. Instrucțiunile care pot genera excepții (apeluri de metode sau instrucțiuni '''throw''') se plasează într-un bloc '''try''' după care apar unul sau mai multe blocuri '''catch''' care administrează efectiv fiecare tip de excepție care poate fi generată:
 +
 +
<syntaxhighlight lang="java">
 +
public class Person{
 +
 +
    private String fullName;
 +
    private int age;
 +
    private boolean gender;
 +
 +
public Person(String _fullName, int _age, boolean _gender) throws Exception{
 +
    //...
 +
    /* setAge() throws a checked exception of type Exception
 +
    * which isn't caught in this method, so this method will
 +
    * throw the exception further up the stack, thus the 'throws Exception'
 +
    * in the method declaration
 +
    */ 
 +
    setAge(_age);
 +
    //..
 +
    System.out.println("If setAge() throws an exception, this line will not be executed!");
 +
}
 +
 +
public static void main(String[] _args){
 +
    try{
 +
        Person _p = new Person("Ghita Vasile", -30, true);
 +
    }catch(Exception _e){
 +
        /* if an exception is thrown by the constructor, the execution
 +
        * is continued with this catch block. The reference _e is to
 +
        * the object that has been thrown. In this particular case,
 +
        * the instantiation of the object is not complete, therefor
 +
        * _p is still null.
 +
        */
 +
        System.out.println("Can't create Person object: " + _e.getMessage());
 +
    }
 +
 +
    /* after the catch block completes, or in case no exception is thrown,
 +
    * the execution continues from here.
 +
    */
 +
    System.out.println("Program done!");
 +
}
 +
 +
public void setAge(int _age) throws RuntimeException{
 +
    if(_age < 0 || _age > 150){
 +
        Exception _e = new Exception("Invalid age " + _age);
 +
        throw _e;
 +
    }
 +
 +
    age = _age;
 +
}
 +
 +
}
 +
</syntaxhighlight>

Versiunea de la data 23 august 2012 08:51

În Java, excepțiile reprezintă o întrerupere în execuția normală a algoritmului. Acestea sunt folosite pentru a administra problemele apărute în timpul execuției și a lua măsurile de rigoare pentru a relua programul din locul în care este posibil. Excepțiile, ca orice altceva în Java, sunt obiecte. Clasa de bază pentru orice tip de excepție este java.lang.Throwable.

Din clasa Throwable se extind două alte clase:

  • java.lang.Error - un tip de excepție care descrie o problemă gravă în execuția programului și din cauza căreia aplicația nu mai poate continua; aceste tipuri de excepții nu pot fi administrate.
  • java.lang.Exception - o clasă care descrie excepții pe care o aplicație le poate administra și după care execuția se poate relua în mod corect;

Generarea excepțiilor

O excepție este generată (aruncată) folosind cuvântul cheie throw:

public void setAge(int _age){
    if(_age < 0 || _age > 150){
        Error _e = new Error("Invalid age " + _age);
        throw _e;
    }

    age = _age;
}

O excepție odată generată, execuția normală a programului se întrerupe și se reia doar într-un bloc catch asociat acelui tip de excepție (vezi #administrarea excepțiilor). Spre exemplu, în situația de mai sus, după ce eroarea a fost generată folosind cuvântul cheie throw, asignarea age = _age; nu se mai execută.

Tratarea excepțiilor

În anumite situații, excepțiile întrerup definitiv execuția programului. Aceste tipuri de excepții nu se administrează (cele extinse din clasa Error). Există totuși excepții care pot fi tratate, cele extinse din clasa Exception. Acestea sunt de două tipuri:

Regulă: Excepțiile checked care nu sunt administrate în metoda curentă trebuie obligatoriu să apară în lista de excepții generate ale metodei. Excepțiile unchecked care nu sunt administrate în metoda curentă NU trebuie obligatoriu să apară în lista de excepții generate ale metodei. Excepțiile de tip Error sunt de tip unchecked.

Lista de excepții checked generate de o metodă se scrie după lista de argumente, dar înainte de corpul metodei, utilizând cuvântul cheie throws:

public void setAge(int _age) throws Exception{
    if(_age < 0 || _age > 150){
        Exception _e = new Exception("Invalid age " + _age);
        throw _e;
    }

    age = _age;
}

Cum clasa Exception este de tip checked, ea trebuie să apară în lista de excepții generată de metodă. În schimb RuntimeException poate să lipsească:

public void setAge(int _age){
    if(_age < 0 || _age > 150){
        RuntimeException _e = new RuntimeException("Invalid age " + _age);
        throw _e;
    }

    age = _age;
}

Propagarea pe stivă

Stiva de execuție a unui program reprezintă secvența de metode apelate una de cealaltă.

public class Person{

    private String fullName;
    private int age;
    private boolean gender;

public Person(String _fullName, int _age, boolean _gender){
    setAge(_age);
} 

public static void main(String[] _args){
    Person _p = new Person("Ghita Vasile", 20, true);
}

public void setAge(int _age){
     /* in this point, the execution stack is as follows:
      * 
      *  /---------------------------------\    ^
      *  |        void setAge(int)         |    |
      *  +---------------------------------+    |
      *  |  Person(String, int, boolean)   |    |
      *  +---------------------------------+    |
      *  |    static void main(String[])   |    |
      *  \---------------------------------/    |
      *
      *  where method main(String[]) is at the 
      *  bottom of the stack (first one called)
      *  and method setAge(int) is on the top
      *  of the stack (last one called), and it's
      *  the method that's currently in execution.
      */
     age = _age;
}

}


În situația în care nici metoda apelantă nu administrează excepția generată, atunci se consideră că și ea la rândul ei generează același tip de excepție, într-un mod recursiv:

public class Person{

    private String fullName;
    private int age;
    private boolean gender;

public Person(String _fullName, int _age, boolean _gender) throws Exception{
    //...
    /* setAge() throws a checked exception of type Exception
     * which isn't caught in this method, so this method will
     * throw the exception further up the stack, thus the 'throws Exception'
     * in the method declaration
     */  
    setAge(_age);
    //..
    System.out.println("If setAge() throws an exception, this line will not be executed!");
} 

public void setAge(int _age) throws RuntimeException{
    if(_age < 0 || _age > 150){
        Exception _e = new Exception("Invalid age " + _age);
        throw _e;
    }

    age = _age;
}

}

Administrarea excepțiilor

Administrarea unei excepții de face într-un bloc try-catch. Instrucțiunile care pot genera excepții (apeluri de metode sau instrucțiuni throw) se plasează într-un bloc try după care apar unul sau mai multe blocuri catch care administrează efectiv fiecare tip de excepție care poate fi generată:

public class Person{

    private String fullName;
    private int age;
    private boolean gender;

public Person(String _fullName, int _age, boolean _gender) throws Exception{
    //...
    /* setAge() throws a checked exception of type Exception
     * which isn't caught in this method, so this method will
     * throw the exception further up the stack, thus the 'throws Exception'
     * in the method declaration
     */  
    setAge(_age);
    //..
    System.out.println("If setAge() throws an exception, this line will not be executed!");
} 

public static void main(String[] _args){
    try{
        Person _p = new Person("Ghita Vasile", -30, true);
    }catch(Exception _e){
        /* if an exception is thrown by the constructor, the execution
         * is continued with this catch block. The reference _e is to 
         * the object that has been thrown. In this particular case, 
         * the instantiation of the object is not complete, therefor
         * _p is still null.
         */
         System.out.println("Can't create Person object: " + _e.getMessage());
    }

    /* after the catch block completes, or in case no exception is thrown,
     * the execution continues from here.
     */
    System.out.println("Program done!");
}

public void setAge(int _age) throws RuntimeException{
    if(_age < 0 || _age > 150){
        Exception _e = new Exception("Invalid age " + _age);
        throw _e;
    }

    age = _age;
}

}