Programmation Orient´ee Objet - univ-lille.fr

26
Exceptions Exceptions Programmation Orient´ ee Objet Licence mention Informatique Universit´ e Lille – Sciences et Technologies Universit´ e Lille – Sciences et Technologies - Licence mention Informatique Programmation Orient´ ee Objet 1

Transcript of Programmation Orient´ee Objet - univ-lille.fr

Exceptions

Exceptions

Programmation Orientee Objet

Licence mention InformatiqueUniversite Lille – Sciences et Technologies

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 1

Exceptions

Comment gerer les « situations problematiques » a l’execution ?par une valeur de retour↪→ difficile a traiterpar des exceptions↪→ signaler la ou le probleme se pose dans le code↪→ separer le traitement des cas « normaux » de celui des casexceptionnels↪→ les cas particuliers sont transmis au gestionnaire d’exceptions(exception handler)

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 2

Exceptions

qu’est ce qu’un cas exceptionnel ?

une situation qui ne correspond au « fonctionnement normal » d’unemethode

diviser un nombre par 0 ArithmeticException

envoyer un message sur unereference null

NullPointerException

acceder a l’element d’un tableauen dehors des indices

ArrayIndexOutOfBoundsException

realiser un transtypage impossible ClassCastException

tenter d’acceder a un fichier quin’existe pas

FileNotFoundException

etc. etc.

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 3

Exceptions

extrait de la javadoc de la classe java.lang.String :

substringpublic String substring(int beginIndex)

Returns a new string that is a substring of this string. Thesubstring begins with the character at the specified indexand extends to the end of this string.

Examples:"unhappy".substring(2) returns "happy""Harbison".substring(3) returns "bison""emptiness".substring(9) returns "" (an empty string)

Parameters:beginIndex - the beginning index, inclusive.

Returns:the specified substring.

Throws:IndexOutOfBoundsException - if beginIndex is negative or

larger than the length of this String object.

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 4

Exceptions

exceptions

des portions de code peuvent lancer (declencher) des exceptionssignes d’un « probleme »il est possible de capturer une exception pour proposer unealternative/solution

en java les exceptions sont des objetsils sont tous du type Exceptionleur classe « exacte » est un « sous-type » de Exception

les classes d’exceptions se nomment par conventionNatureDuProbleme Exception

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 5

Exceptions

quelques methodes du type Exception

public void printStackTrace()public String getMessage()public String getLocalizedMessage()

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 6

Exceptions

0 package exception;1 public class TestException {2 private int[] tab;3 public TestException() {4 this.tab = new int[2];5 for(int i= 0; i < this.tab.length; i++) { this.tab[i]= i; }6 }7 public void displayElements(int limit) {8 for(int i= 0; i < limit; i++) {9 System.out.println(this.tab[i]);10 }11 }12 public void go(int limit) {13 this.displayElements(limit);14 }15 public static void main(String[] args) {16 TestException ref = new TestException();17 ref.go(Integer.parseInt(args[0]));19 System.out.println("execution reaches this point ?");20 }21 }

== EXECUTION ==$ java -classpath classes exception.TestException 3

01Exception in thread ”main” java.lang.ArrayIndexOutOfBoundsException: 2

at TestException.displayElements(TestException.java:9)at TestException.go(TestException.java:13)at TestException.main(TestException.java:17)

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 7

Exceptions

1 public class TestException1 {2 private int [ ] tab ;3 public TestException1() {4 this . tab = new int [ 2 ] ;5 for ( int i = 0; i < this . tab . length ; i++) { this . tab [ i ] = i ; }6 }7 public int sumOfLimitElements( int l imit ) {8 int sum = 0;9 for ( int i = 0; i < l imit ; i++) {

10 sum = sum + this.tab[i] ;11 }12 return sum;13 }14 public int go( int l imit ) {15 int result = 0;16 result = this.sumOfLimitElements(limit) ;17 return result ;18 }19 public static void main( String [ ] args) {20 TestException1 ref = new TestException1 () ;21 int result = ref.go(Integer.parseInt(args[0])) ;22 System. out . pr int ln ("result = "+result ) ;23 System. out . pr int ln ("execution reaches this point ?") ;24 }25 }

== EXECUTION ==$ java -classpath classes exception.TestException1 3Exception in thread ”main” java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2

at exception.TestException1.sumOfLimitElements(TestException1.java:10)at exception.TestException1.go(TestException1.java:16)at exception.TestException1.main(TestException1.java:21)

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 8

Exceptions

javadoc

les exceptions se documentent @exception/throws

/∗∗ sum the ’ l imit ’ f i r s t elements of tab∗ @param l imit number of head elements of tab to be added∗ @return the sum of the ’ l imit ’ f i r s t elements of tab∗ @exception ArrayIndexOutOfBoundsException i f l imit < 0 or > number∗ of elements (here 2)∗/

public int sumOfLimitElements( int l imit ) {int sum = 0;

for ( int i = 0; i < l imit ; i++) {sum = sum + this . tab [ i ] ;}return sum;

}

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 9

Exceptions

capturer une exception

quand une portion de code est susceptible de lancer une exception, on peut1 essayer d’executer ce code « normalement »,2 et capturer l’exception si elle se produit

pour indiquer le traitement qui doit en etre fait dans ce cas.

try {... code susceptible de lancer une exception

}catch (ClasseDException e) {

... traitement a executer si exception}

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 10

Exceptions

exemple

public class SomeClass {public String endOfTimo( int index) {

String result ;try {

result = "timoleon" . substring ( index ) ;}catch (IndexOutOfBoundsException e) {

i f ( index < 0) result = "timoleon" ;i f ( index > 8) result = "" ;

}return result ;

}}

// u t i l i s a t i onsomeRef .endOfTimo(2) ; // −> ”moleon”someRef .endOfTimo(-1) ; // −> ”timoleon”someRef .endOfTimo(12) ; // −> ””

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 11

Exceptions

exemple (2)

equals() autrement :

public class Item {. . .public boolean equals (Object o) {

try {Item other = (Item) o; // exception s i o /∈ Item ( cast i l l egal )return ( this . price == other . price ) && this . id . equals (other . id ) ;

}catch (ClassCastException e) {

return false ;}

}}

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 12

Exceptions

lorsqu’une exception levee est capturee, on n’arrete pas le fluxd’execution du programme,on quitte un bloc try des qu’une exception est levee dans ce bloc,le flux d’execution reprend « apres » le bloc,si l’exception est capturee, le traitement associe a cette capture estexecute,le flux d’execution se poursuite « apres » le bloc catch,un meme bloc peut etre susceptible de lever plusieurs exceptions,il est possible de les traiter separement ou globalement

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 13

Exceptions

1 public class TestException2 {2 ... idem ...3 public int sumOfLimitElements( int l imit ) {4 ... idem ...5 }6 public int go( int l imit ) {7 int result = 0;8 try {9 result = this . sumOfLimitElements( l imit ) ;

10 System. out . pr int ln ("go(): OK, result obtained") ;11 }12 catch (ArrayIndexOutOfBoundsException e) {13 System. out . pr int ln ("go(): GOT IT") ;14 result = Integer .MIN VALUE; // code correct i f15 }16 System. out . pr int ln ("go(): AFTER") ;17 return result ;18 }1920 public static void main( String [ ] args) {21 TestException2 ref = new TestException2 () ;22 int result = ref .go( Integer . parseInt (args [ 0 ] ) ) ;23 System. out . pr int ln ("result = "+result ) ;24 System. out . pr int ln ("execution reaches this point ?") ;25 }26 }

== EXECUTION ==$ java -classpath classes exception.TestException2 3

go(): GOT ITgo(): AFTERresult = -2147483648execution reaches this point ?

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 14

Exceptions

captures multiples

captures separeestry {

x = 1/obj . getValue () ;}catch (NullPointerException e) {

System. out . pr int ln ("obj is null") ;}catch (ArithmeticException e) {

System. out . pr int ln ("obj.getValue() == 0") ;}

capture de toutes les exceptionstry {

x = 1/obj . getValue () ;}catch (Exception e) {

System. out . pr int ln ("exception: "+e . getMessage ()) ;}

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 15

Exceptions

cas de non captureSi une methode contient une portion de code susceptible de lancer uneexception et que l’on ne souhaite pas (ou ne peut pas) traiter l’exceptiondans le corps de la methode, il est necessaire d’informer l’utilisateur de lamethode que celle-ci peut generer une exceptione:

ajouter throws ClasseDException a la signature de la methode+ documentation : @exception

public class SomeClass {private String name;...public int endOfName(int endLength) throws IndexOutOfBoundsException {

return this.name.substring(this.name.length()-endLength);}public FileReader openFile() throws FileNotFoundException {

return new FileReader(this.name);}

}

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 16

Exceptions

1 public class TestException3 {2 ... idem ...3 /∗∗4 ∗ @param l imit number of values to sum5 ∗ @exception ArrayIndexOutOfBoundsException i f l imit i s greater than size of tab6 ∗/7 public int go( int l imit ) throws ArrayIndexOutOfBoundsException {8 return this . sumOfLimitElements( l imit ) ;9 }

1011 public static void main( String [ ] args) {12 TestException3 ref = new TestException3 () ;13 int result ;14 try {15 result = ref .go( Integer . parseInt (args [ 0 ] ) ) ;16 }17 catch (ArrayIndexOutOfBoundsException e) {18 System. out . pr int ln ("main(): GOT IT") ;19 result = −1000; // code correct i f20 }21 System. out . pr int ln ("result = "+result ) ;22 System. out . pr int ln ("execution reaches this point ?") ;23 }24 }

== EXECUTION ==$ java -classpath classes exception.TestException3 3

main(): GOT ITresult = -1000execution reaches this point ?

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 17

Exceptions

il est possible qu’une methode soit susceptible de declencher plusieursexceptions :

public void someMethod(args ) throws Exception1, ..., ExceptionN {...

}

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 18

Exceptions

declencher une exception

pour declencher une exception explicitement dans une portion de code :1 creer un objet exception (de la classe d’exception voulue)2 « lancer » l’exception a l’aide de throw3 la signature de la methode doit annoncer (throws) l’exception

bien choisir le nom de la classe de l’exception lancee,il doit aider a identifier le type de probleme

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 19

Exceptions

1 public class TestException4 {2 ... idem ...3 /∗∗4 ∗ @param l imit number of values to add5 ∗ @exception IllegalArgumentException i f l imit i s greater than size of tab6 ∗/7 public int go( int l imit ) throws IllegalArgumentException {8 i f ( l imit > this . tab . length)9 throw new IllegalArgumentException("limit too high: "+limit ) ;

10 return this . sumOfLimitElements( l imit ) ;11 }1213 public static void main( String [ ] args) {14 TestException4 ref = new TestException4 () ;15 try {16 System. out . pr int ln ("result = "+ ref .go( Integer . parseInt (args [ 0 ] ) ) ) ;17 }18 catch(IllegalArgumentException e) {19 System. out . pr int ln ("main(): GOT IllegalArgumentException") ;20 System. out . pr int ln ("result cannot be computed") ; // code correct i f21 }22 System. out . pr int ln ("execution reaches this point ?") ;23 }24 }

== EXECUTION ==$ java -classpath classes exception.TestException4 3

main(): GOT IllegalArgumentExceptionresult cannot be computedexecution reaches this point ?

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 20

Exceptions

Exception et Test

Tester la specification de leveer d’exception par une methode :adapter l’annotation de la methode de test

@Test(expected=XxxException.class)construire la logique du test pour arriver a une situation devantdeclencher l’exception indiqueele test reussit ssi l’execution de la methode de test declenchel’exception indiqueeet valide les autres assertions eventuellement presentes

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 21

Exceptions

La methode qui calcule la date atteinte n jours apres doit declencherune exception IllegalArgumentException si son parametre estnegatif.

dans Date

public Date nbDaysAfter(int nbDays) throws IllegalArgumentException

@Test(expected=IllegalArgumentException.class)public void dateAfterNbDaysThrowsExceptionIfNbNegative() throws Exception {

Date d = new Date(14, Month. july , 1789);d. nbDaysAfter( −2 ) ;}

le test est reussi si une IllegalArgumentException est lancee

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 22

Exceptions

plus rigoureusement :

s’assurer que l’exception n’est declenchee que si le parametre est < 0

@Test(expected=IllegalArgumentException.class)public void dateAfterNbDaysThrowsExceptionIfNbNegative() throws Exception {

Date d = new Date(14, Month. july , 1789);try {

d. nbDaysAfter( +2 ); // ne doit pas lancer d ’ exception}catch( IllegalArgumentException e) {

f a i l ( ) ; // test echoue s i exception quand nb > 0}

d. nbDaysAfter( −2 ) ; // doit lancer l ’ exception}

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 23

Exceptions

reexecuter le bloc try apres correction d’une erreur :

boolean done = false;while (! done) {

try {... traitement avec levee d’exception possibledone = true;

} catch(ClasseDException e) {... correction problemedone = false; // ou done deja a false

}}

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 24

Exceptions

exemple : saisie d’un nombre

public class Input {public static int readInt() throws java.io.IOException {

try {return Input.scanner.nextInt();

} catch (Exception e) {Input.scanner.skip(".*");throw new java.io.IOException();

}}

} // Input

====UTILISATION====================================================================int value = -1;while (value < 0) {

try {System.out.print("Enter a positive integer : ");value = Input.readInt();

} catch(IOException e) {// input string does not match with a numberSystem.out.println("You must provide an integer.");

}}

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 25

Exceptions

a venir

pourquoi toutes les exceptions n’ont pas necessairement besoin d’etrecapturees ou signalees (ce sont les “RuntimeException”) ?creer ses propres classes d’exceptions

Universite Lille – Sciences et Technologies - Licence mention Informatique Programmation Orientee Objet 26