Professional Documents
Culture Documents
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
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
OOSE 9 15 OOSE 9 16
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
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
OOSE 9 27 OOSE 9 28
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
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
OOSE 9 39 OOSE 9 40
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
OOSE 9 45