You are on page 1of 8

Polytech’Montpellier – IG4

Object-Oriented Software
Java exceptions
Engineering
Lecture 9
Exceptions

Errors/Exceptions Errors/Exceptions
•  Ideally, it should be possible to detect any error at •  You should use the exception mechanism only to
compile time. However, this is not always possible handle the abnormal behavior in a certain part of
and therefore errors should be treated also at your program (generated by an error or an
execution time. exceptional case)
•  Java proposes a mechanism to handle errors. Its •  In Java, an error will not brutally stop the
philosophy is to allow the code generating the execution of a program, but the creation of an
error to provide sufficient information to the code object, instance of a class purposefully created to
that knows how to handle that error. be associated to an error/exception case.

OOSE 9 3 OOSE 9 4

Use of errors/exception
Example of errors/exceptions
mechanism
// t – reference to an object
if (t == null) •  Rather than complicating the algorithm, the
throw new NullPointerException ();
abnormal situations are treated separately.
public class Livre { •  The “normal” part is hence more simple to
. . .
public void setPrix(double prix) {
if (prix >= 0)
understand and readable
else
this.prix = prix;
•  The error treatment is made inside a special
// Création d’une instance
throw new IllegalArgumentException("Prix négatif !"); zone of the program called exception
}
. . .
}
handler (catch block)

OOSE 9 5 OOSE 9 6

1
Exception treatment try-catch block
try {
int n; // part that, maybe, generates exceptions
try { // Normal treatment . . .
// read an int from console and assign it to n }
. . . catch(Type1Exception e1) {
etagere.add(livre, n); // Treatment of exceptions of type Type1
} . . .
catch(NumberFormatException e) { }
System.err.println("Mauvais numéro de livre"); catch(Type2Exception e2) {
} // Treatment of exceptions of type Type2
. . .
}
// etc.

OOSE 9 7 OOSE 9 8

Terminology Exception handling mechanism


•  An instruction or a method can raise or throw an
exception, that is, an abnormal behaviour
generates the creation of an exception.
•  A method can catch, handle, treat an exception in
a catch clause inside a try-catch block
•  A method can let propagate an exception:
–  It does not catch the exception in a catch clause
–  The error will go “upper” towards the calling method
which, maybe, knows how to treat the error or let it
propagate further.
OOSE 9 9 OOSE 9 10

Exception raised from outside of Exception raised from inside of


try block try block
•  The method returns immediately; the •  If one of the instructions from inside a try block
exception is thrown to the calling method produces an exception, the next instructions from
the try block will not be executed and:
•  The treatment is left to the calling method –  if at least one of the catch clauses corresponds to the
•  The exception might be handled by the type of the exception
•  the first catch clause is executed,
calling method
•  the execution continues further after the try-catch block.
–  otherwise,
•  the method returns immediately,
•  the exception is thrown to the calling method.

OOSE 9 11 OOSE 9 12

2
Exception raised from inside of Execution without exception in a
try block try block
•  If an exception is handled inside a catch •  If after executing all the try block, no
block and if inside that block there is a instruction raises an exception, the program
return, break or continue continues to be executed immediately after
command, the execution continues from the try-catch block.
place corresponding to one of these
commands, and not after try-catch.

OOSE 9 13 OOSE 9 14

Default exception handling Treatments inside catch


•  If an exception is not handled any where •  Fix an error and retry the execution of the code
(not even by main()) then the JVM that raised the error
– stops the program execution, •  Make an alternative treatment
– displays an error message and the content of •  Return from the method with a particular value
stack of the method calls traversed by the •  Exit from the application System.exit()
exception. •  Execute a partial treatment and raise (throw) a
new or the same exception to be caught (treated)
by superior calling methods.

OOSE 9 15 OOSE 9 16

Flexibility while handling Frequent errors when exception


exceptions handling
•  The method containing the erroneous behavior •  If a variable is:
can: –  Declared and initialized in a try block and
–  Handle the anomaly –  Used after the try block,
•  To continue after the normal execution of the program, the compiler will produce an error of the
•  Or to make a special treatment, different from the normal one. following type: “undefined variable” or “Variable
–  Do nothing, and leave the decision about the choice of xx may not have been initialized”
treatment to the calling method which maybe has more •  In order to avoid this, you should declare (and
information to do a correct treatment. initialize if necessary) the variable before the try
–  Do a partial treatment of the anomaly and leave to the block
calling methods the responsibility of finishing the job.
OOSE 9 17 OOSE 9 18

3
Incorrect declaration Correct declaration
try { int n=0; // déclaration/intialisation hors du bloc try
int n; try {
n = Integer.parseInt(args[0]); n = Integer.parseInt(args[0]);
etagere.add(livres[n]); etagere.add(livres[n]);
} }
catch(NumberFormatException e) { catch(NumberFormatException e) {
System.err.println("Mauvais numéro de livre"); System.err.println("Mauvais numéro de livre");
return; return;
} }
catch {EtagerePleineException e) { catch {EtagerePleineException e) {
System.err.println("Etagere pleine"); System.err.println("Etagere pleine");
return; return;
} }
n++; // provoque une erreur à la compilation n++; // pas d’erreur à la compilation

OOSE 9 19 OOSE 9 20

Exception types Classes of errors/exceptions


•  All the classes related to errors/exceptions
are placed into a inheritance hierarchy that
has as root the class Throwable
•  JDK provides you with a certain number of
classes,
•  But you can add new ones and place them
in the same inheritance hierarchy of
Throwable

OOSE 9 21 OOSE 9 22

Some subclasses of
Exception inheritance tree
RuntimeException
Throwable
• NullPointerException
• IndexOutOfBoundsException and its
Error Exception
subclass
ArrayIndexOutOfBoundsException
RunTimeException Controlled • ArithmeticException
Exceptions
• IllegalArgumentException and its
subclass NumberFormatException
JDK
Predefined
Programmer
Defined
• ClassCastException
Exceptions Exceptions
• NoSuchElementException
OOSE 9 23 OOSE 9 24

4
JDK exceptions controlled by the
“Controlled” exceptions
compiler
Exception
•  Exceptions that inherit from Exception but which
are not RuntimeException
•  The compiler checks if the methods handle them
ClassNotFound
Exception
IOException Interrupted
Exception
correctly.
•  Any method that potentially raises a controlled
exception MUST declare it in its declaration
EOFException FileNotFound
Exception int m() throws TrucException {
. . .
}

OOSE 9 25 OOSE 9 26

Controlled exceptions Grouping exceptions


•  Let m2() be a method that declares “throws •  The inheritance tree starting from Throwable
TrucException” actually allows you to group together all the
•  If another method m1() calls m2() subclasses of a given exception class
–  either m1() handles the exception in a try–catch block •  For instance,
surrounding the call of m2() catch(IOException e) { . . .}
–  or m1() is declared as throwing the same kind of groups exceptions due to input/output operations
exception as m2() (or a more general exception type) such as EOFException, FileNotFoundException.

OOSE 9 27 OOSE 9 28

Exception or normal treatment? Methods of Throwable


•  You should make use of exceptions only to handle •  Throwable has 2 constructors : the no-argument
possible errors or exceptional situations. You constructor and a constructor with one String argument
should avoid the use of exceptions to handle (used to describe the context of the error)
“normal” cases. For instance: •  getMessage() returns the error message associated to an
–  When reading sequentially from a file, you should not instance of Throwable (getLocalizedMessage(): idem
use EOFException to identify the EOF. You can use but in the local language)
instead a special value that is returned by the method •  printStackTrace() prints to the standard error
that reads from the file when it encounters the EOF. (System.err), the error message and the stack trace of all
–  But, if you encouter the EOF before reading the 10 the method calls from main() to the place that generated
values the you put before in a file, then you should use the exception.
EOFException
OOSE 9 29 OOSE 9 30

5
Clause finally finally is always executed
•  The finally clause contains the treatment that •  The finally block is always executed (except for
will be executed in any case, regardless if in try System.exit()), even if try or catch ends by a
blocck there was or not an exception. return or throws an exception.
•  If the try block produces an exception
try {
. . . –  if catch handles it, the block finally is executed
}
catch (. . .) { after.
. . .
} –  if no catch block handles the exception, finally is
finally { executed, and then the exception propagates back to the
. . .
} calling method.
// On peut, par exemple, fermer un fichier

OOSE 9 31 OOSE 9 32

Prédominance du bloc finally Throw exceptions


•  Le bloc finally « l’emporte » sur les blocs •  You, as programmer, can write methods that
catch et try throw exceptions
•  Si le bloc finally se termine par un return, la
•  You can throw exceptions, instances of
méthode retournera avec la valeur de ce return,
quelque soit ce qui s’est passé dans les blocs try
exception classes provided by JDK
et catch •  Or throw exceptions, instances of new
•  Si le bloc finally lance une exception, la classes written by you and which are more
méthode lance cette exception, quelque soit ce qui suitable to the problem you try to solve.
s’est passé dans les blocs try et catch
OOSE 9 33 OOSE 9 34

Throw exceptions: JDK


Writing a new exception class
exceptions
public class Livre {
. . .
public void setPrix(double prix) {
if (prix >= 0)
this.prix = prix;
else
// Création d’une instance
throw new IllegalArgumentException("Prix négatif !");
}
. . .
}

OOSE 9 35 OOSE 9 36

6
Writing a new exception class Use of a new exception class
•  The convention is to name an exception
public class Etagere {
class using the Exception suffix . . .
public void ajouteLivre(Livre livre)
throws EtagerePleineException {
if (nbLivres < livres.length)
public class EtagerePleineException extends Exception { livres[nbLivres++] = livre;
private Etagere etagere; else
public EtagerePleineException(Etagere etagere) { throw new EtagerePleineException(this);
this.etagere = etagere; // L’instance de l’exception contiendra une référence
} // à l’étagère pleine
public Etagere getEtagere() { }
return etagere; . . .
} }
}

OOSE 9 37 OOSE 9 38

A different way to write


Catching the new exception
ajouteLivre
Etagere etagere = new Etagere(10);// étagère de 10 livres
public void ajouteLivre(Livre livre) throws EtagerePleineException { ...
try { try {
livres[nbLivres++] = livre; etagere.ajouteLivre(new Livre("Thinking in Java", "Eckel"));
} }
catch(ArrayOutOfBoundException e) { catch(EtagerePleineException e) {
throw new EtagerePleineException(this); System.err.println("L’étagère ne peut contenir que "
} + e.getEtagere().getContenance());
} e.printStackTrace();
}

OOSE 9 39 OOSE 9 40

Example - LinkedList Example - LinkedList


•  Let’s suppose that you want to write a • LinkedList should inform its clients
package for lists. The LinkedList class the kind of error its methods raise:
can contain the following methods: Object objectAt(int n)– exception if n
Object objectAt(int n) is lower than 0 or greater than the number of
Object firstObject() elements.
int indexOf(Object o) Object firstObject()– exception if
empty list
int indexOf(Object o) – exception if
the object is not in the list
OOSE 9 41 OOSE 9 42

7
Example - LinkedList Example - LinkedList
•  How to choose the exception type? •  The LinkedList class can throw many exception types. It
–  Use the existing classes would be useful to catch them by one shot. Therefore you
–  Write your exception class should use the following hierarchy:
•  Write your exception class if: LinkedListException
–  Need of a type not existing in JDK
–  Help you differentiate between your types and those proposed by
other editors.
InvalidIndexException ObjectNotFoundException
–  The code throws many very closed exception types
–  Your code uses many different types written by someone else and
which are not available to clients of your class. EmptyListException

OOSE 9 43 OOSE 9 44

Knowing how to read an error


message
•  The error messages printed by the JVM
correspond to the execution of
printStackTrace()
•  Reading carefully these messages helps you
rapidly recover from an error.

OOSE 9 45

You might also like