ITI 1121. Introduction to Computing II – subtitle
ITI 1121. Introduction to Computing II
Error handling in Java
by
Marcel Turcotte
Version February 24, 2020
Summary
Error handling in Java
Modern programming languages offer mechanisms for error handling. In Java, we will see
that an error situation is modeled using an object. We will see how to signify an error and
understand the consequences on the flow of control. Finally, we will look at two ways to
handle errors.
General objective :
Following this lesson, you will be able to report and handle errors in Java.
1 65
Learning objectives
Name some types of Java exceptions.
Trace the execution of a program following the execution of a throw statement.
Explain the following statement: Exceptions are either checked or unchecked.
Modify an application to signify errors using exceptions.
Modify an application to handle error situations.
Create new types of exceptions.
Readings:
Pages 29–36, 559, 608–619 of E. Koffman and P. Wolfgang.
2 65
Plan
1 Error handling
2 Exception
3 Throw
4 Try-Catch
5 Throws
6 New types
3 65
Error handling
Theory : Error handling
Objectifs d’apprentissage :
Distinguish compilation errors from runtime errors
Develop preconditions for a class method
Develop preconditions for an instance method
4 65
Error handling
Introduction
Computer programming disasters
Give examples of programming errors that have led to disasters.
5 65
Self-driving cars
Source: Grendelkhan
6 65
https://theconversation.com/the-everyday-ethical-challenges-of-self-driving-cars-92710
Compilation errors and execution errors
There are two types of errors: compilation errors and execution errors.
Compilation :
Syntax errors
Java being a strongly typed language, the compiler also checks the type of each
expression, which allows the detection of some errors as soon as possible, before the
execution of the program. Type checking ensures that operations on a value are
valid for the type of the value.
Compilation errors don’t affect the users!
7 65
Discussion : Runtime errors
Give examples of run-time errors!
8 65
Discussion : Sources of runtime errors
Name the sources of the run-time errors!
∗As a consequence, we will see that Java also offers us two ways to deal with error situations.
9 65
Error handling
Preconditions
Preconditions
A precondition is a condition that should be met before a method is executed.
In object-oriented programming, we need to validate not only the parameter values,
but also the state of the object.
10 65
A method must begin with the
validation of the preconditions!
Error handling : What to do?
12 65
Desired features
Detecting and handling error situations helps make programs more robust.
Indicate the source of the error precisely.
What method? What statement? What is the nature of the error?
Force the software to take action to correct the situation. (impossible to ignore errors)
13 65
Exception
Exception
Learning objectives :
Summarize the role of the class Exception
14 65
Exception
The class Exception
Exception is a class!
Throwable
−message: String
+getMessage(): String
+printStackTrace(): void
+String(): toString
Object
ExceptionError
RuntimeExceptionIOException
ArithmeticException
IllegalArgumentException
NumberFormatException
IllegalStateException IndexOutOfBoundsException
NullPointerException
…
15 65
Exception is a class!
Exceptions are objects!
An error situation is modeled using an object of the class Throwable, or one of its
subclasses.
The object encapsulates an error message.
Among others, the class Throwable declares the methods String getMessage() and
void printStackTrace().
16 65
Exception
Variable of type Exception
Declaring a variable of type Exception
Declaring a reference of type Exception is not exceptional.
Excep t i on e ;
17 65
Exception
Object from the class Exception
Creating an object of the class Exception
Likewise, there’s nothing exceptional about creating an object of the class Exception.
e = new Excep t i on ( “Houston , we ’ ve had a problem ! ” ) ;
The line “Houston, we’ve had a problem” became famous after the movie “Apollo 13”.
18 65
Throw
Signaling an error situation
Learning objectives:
Modifying an application to signify errors using exceptions.
Trace the execution of a program following the execution of a throw statement.
Readings:
Pages 559, 608–619 of E. Koffman and P. Wolfgang.
19 65
Signaling an error situation
Let’s consider the implementation of a stack using linked elements and its method
pop().
Removing an element when the stack is empty is an error situation.
Formulate a test to validate the precondition of the pop method.
20 65
Throw
Throw statement
Throw statement
In Java, the statement “throw” alters the normal flow of control. Its argument is a
reference to an object of the class Throwable or one of its subclasses.
21 65
Throw statement
22 65
Throw
Transfer of control
Transfer of control
When an exceptional situation is reported,
The statement or expression ends abruptly;
If the exception is not processed, the stack of method calls will be completely
unwound, i.e. each method call on the execution stack will end abruptly, and the
execution of the program will end with the printing of the stack at the time of the
error (“stack trace”);
No statements and no parts of the expression after the expression that caused the
error will be executed;
following an exception, the next statements executed are those in a catch or finally
block.
23 65
Throw
Examples
c l a s s Test {
pub l i c s t a t i c vo id main ( S t r i n g [ ] a r g s ) {
System . out . p r i n t l n ( ” Labe l 1″ ) ;
i f ( a r g s . l e n g t h == 0) {
throw new Runt imeExcept ion ( “Houston . . . ” ) ;
}
System . out . p r i n t l n ( ” Labe l 2″ ) ;
}
}
24 65
Houston, we’ve had a problem!
Following the statement throw, the method terminates abruptly.
> java Test
Label 1
Exception in thread “main” java.lang.RuntimeException:
Houston, we’ve had a problem!
at Test.main(Test.java:5)
Thus, the string “Label 2’’ will not be displayed on the console.
25 65
pub l i c c l a s s Test {
pub l i c s t a t i c boolean e r r o r ( i n t v ) {
i f ( v == 0) {
throw new Runt imeExcept ion ( “Oops ! I ’m s o r r y . ” ) ;
}
re tu rn t rue ;
}
pub l i c s t a t i c boolean d i s p l a y ( ) {
System . out . p r i n t l n ( ” Labe l 2″ ) ;
re tu rn t rue ;
}
pub l i c s t a t i c vo id main ( S t r i n g [ ] a r g s ) {
System . out . p r i n t l n ( ” Labe l 1″ ) ;
i f ( e r r o r (0 ) | | d i s p l a y ( ) ) {
System . out . p r i n t l n ( ” Labe l 3″ ) ;
}
System . out . p r i n t l n ( ” Labe l 4″ ) ;
}
}
Compile and run the above program.
26 65
Oops! I’m sorry
Following the throw statement, the method error terminates abruptly, likewise, the
method main terminates abruptly.
> java Test
Label 1
Exception in thread “main” java.lang.RuntimeException:
Oops! I’m sorry.
at Test.error(Test.java:5)
at Test.main(Test.java:16)
Thus, the strings “Label 2”, “Label 3” and “Label 4” will not be displayed on the
console.
27 65
pub l i c c l a s s Test {
pub l i c s t a t i c vo id c ( ) {
System . out . p r i n t l n ( ” c : Labe l 1″ ) ;
i f ( t rue ) {
throw new Runt imeExcept ion ( ” d e s s u s de l a p i l e ” ) ;
}
System . out . p r i n t l n ( ” c : Labe l 2″ ) ;
}
pub l i c s t a t i c vo id b ( ) {
System . out . p r i n t l n ( “b : Labe l 1” ) ;
c ( ) ;
System . out . p r i n t l n ( “b : Labe l 2″ ) ;
}
pub l i c s t a t i c vo id a ( ) {
System . out . p r i n t l n ( ” a : Labe l 1″ ) ;
b ( ) ;
System . out . p r i n t l n ( ” a : Labe l 2″ ) ;
}
pub l i c s t a t i c vo id main ( S t r i n g [ ] a r g s ) {
System . out . p r i n t l n ( “main : Labe l 1” ) ;
a ( ) ;
System . out . p r i n t l n ( “main : Labe l 2” ) ;
}
}
28 65
Unwind the call stack
> java Test
main: Label 1
a: Label 1
b: Label 1
c: Label 1
Exception in thread “main” java.lang.RuntimeException:
dessus de la pile des appels
at Test.c(Test.java:6)
at Test.b(Test.java:11)
at Test.a(Test.java:16)
at Test.main(Test.java:21)
29 65
pub l i c E pop ( ) {
i f ( i sEmpty ( ) ) {
throw new EmptyStackExcept ion ( ) ;
}
E saved ;
saved = elems[−−top ] ;
e l ems [ top ] == nu l l ;
re tu rn saved ;
}
If the precondition is not satisfied, the method signals an error situation.
Otherwise, the method removes the first item in the stack, and returns its value.
30 65
Try-Catch
Theory
Learning objectives :
Modifying an application to handle error situations.
Tracing the execution of a program following the execution of a throw statement, but
in the presence of try-catch statements.
Readings:
Pages 559, 608–619 of E. Koffman and P. Wolfgang.
31 65
Try-Catch
Syntax
Handling Exceptions
The bloc try/catch is used to regain control when an error situation has occurred.
t r y {
// . . .
} catch ( Except ionType1 i d1 ) {
// s t a t emen t s ;
} catch ( Except ionType2 i d2 ) {
// s t a t emen t s ;
} f i n a l l y {
// s t a t emen t s ;
}
If no exceptions are thrown, only the statements in the try block and the finally block will
be executed.
32 65
Try-Catch
Example
pub l i c c l a s s G r i l l {
p r i v a t e Burner bu rne r = new Burner ( ) ;
pub l i c vo id cook ing ( ) {
t r y {
bu rne r . on ( ) ;
addSteak ( ) ;
addSaltAndPepper ( ) ;
boolean done = f a l s e ;
whi le ( ! done ) {
done = checkSteak ( ) ;
}
} catch ( OutOfGazExcept ion e1 ) {
c a l l R e t a i l e r ( ) ;
} catch ( F i r e E x c e p t i o n e2 ) {
e x t i n g u i s h F i r e ( ) ;
} f i n a l l y {
bu rne r . o f f ( ) ;
}
}
}
33 65
Example: try/catch
i n t DEFAULT_VALUE = 0 ;
i n t v a l u e ;
t r y {
va l u e = I n t e g e r . p a r s e I n t ( ” 100 ” ) ;
} catch ( NumberFormatException e ) {
v a l u e = DEFAULT_VALUE;
}
System . out . p r i n t l n ( ” v a l u e = ” + va l u e ) ;
34 65
How do we know what kind of exception
might be thrown?
35 65
Example: try/catch
i n t DEFAULT_VALUE = 0 ;
i n t v a l u e ;
t r y {
va l u e = I n t e g e r . p a r s e I n t ( ” cen t ” ) ;
} catch ( NumberFormatException e ) {
v a l u e = DEFAULT_VALUE;
}
System . out . p r i n t l n ( ” v a l u e = ” + va l u e ) ;
36 65
Try-Catch
Flow of control
Flow of control
When an exception is thrown, the execution of the statements of the block try ends
(abruptly) and continues with the statements of the first block catch whose parameter
is of the same type as that of the object modeling the error situation, or of a more
general type, followed by the execution of the statements of the block finally, if
present.
No other blocks will be executed.
If no catch block is appropriate, then the exception percolates.
Statements in the finally block are always executed: with or without error.
Finally blocks are used to close open files, for example, or in general, to deal with post
conditions.
37 65
Try-Catch
Comprehensive example
pub l i c c l a s s Test {
pub l i c s t a t i c vo id c ( ) {
System . out . p r i n t l n ( ” c ( ) : : about to throw e x c e p t i o n ” ) ;
throw new Runt imeExcept ion ( ” from c ( ) ” ) ;
}
pub l i c s t a t i c vo id b ( ) {
System . out . p r i n t l n ( “b ( ) : : pre−” ) ;
c ( ) ;
System . out . p r i n t l n ( “b ( ) : : post−” ) ;
}
pub l i c s t a t i c vo id a ( ) {
System . out . p r i n t l n ( ” a ( ) : : pre−” ) ;
t r y {
b ( ) ;
} catch ( Runt imeExcept ion e ) {
System . out . p r i n t l n ( ” a ( ) : : caught e x c e p t i o n ” ) ;
}
System . out . p r i n t l n ( ” a ( ) : : c a l l i n g b , no t r y b l o c k ” ) ;
b ( ) ;
System . out . p r i n t l n ( ” a ( ) : : post−” ) ;
}
pub l i c s t a t i c vo id main ( S t r i n g [ ] a r g s ) {
System . out . p r i n t l n ( ” main ( . . . ) : : pre−” ) ;
a ( ) ;
System . out . p r i n t l n ( ” main ( . . . ) : : post−” ) ;
}
}
38 65
Try-Catch
The reference of type Exception
About the parameter of the block catch
i n t DEFAULT_VALUE = 0 ;
i n t v a l u e ;
t r y {
va l u e = I n t e g e r . p a r s e I n t ( ” douze ” ) ;
} catch ( NumberFormatException e ) {
System . out . p r i n t l n ( ” warn ing : ” + e . getMessage ( ) ) ;
v a l u e = DEFAULT_VALUE;
}
The parameter e is a reference designating the object passed to the statement throw,
as for any other object, the dot notation is used to access the methods of the object.
39 65
Throws
Theory
Learning objectives:
Explain the following statement: Exceptions are either checked or un-checked.
Lectures:
Pages 559, 608–619 of E. Koffman and P. Wolfgang.
40 65
Throws
Mandatory declaration or not
Checked or unchecked
Throwable
−message: String
+getMessage(): String
+printStackTrace(): void
+String(): toString
Object
ExceptionError
RuntimeExceptionIOException
ArithmeticException
IllegalArgumentException
NumberFormatException
IllegalStateException IndexOutOfBoundsException
NullPointerException
…
The descendants of the class Exception are checked.
41 65
Checked or unchecked
Throwable
−message: String
+getMessage(): String
+printStackTrace(): void
+String(): toString
Object
ExceptionError
RuntimeExceptionIOException
ArithmeticException
IllegalArgumentException
NumberFormatException
IllegalStateException IndexOutOfBoundsException
NullPointerException
…
Except if they are subclasses of the class RuntimeExcetion, then they are
unchecked.
42 65
Discussion: Sources of runtime errors
43 65
Checked exceptions
A method using a method that can throw a checked exception shall:
Handle the exception (catch), or;
Let the exception flow and declare it (throws).
44 65
Throws
Syntax
Declaring an exception
The statement throws is used to declare one or more exceptions.
Here we inform users of the method do that it might throw an exception of the type
IOException.
pub l i c s t a t i c vo id do ( S t r i n g name ) throws IOExcept i on {
// . . .
}
45 65
Throws
Example
import j a v a . i o . ∗ ;
pub l i c c l a s s Keyboard {
pub l i c s t a t i c i n t g e t I n t ( ) {
byte [ ] b u f f e r = new byte [ 256 ] ;
System . i n . r ead ( b u f f e r ) ; // throws IOExcept ion
S t r i n g s = new S t r i n g ( b u f f e r ) ;
i n t num = I n t e g e r . p a r s e I n t ( s . t r im ( ) ) ;
re tu rn num ;
}
pub l i c s t a t i c vo id main ( S t r i n g [ ] a r g s ) {
System . out . p r i n t ( ” P l e a s e e n t e r a number : ” ) ;
i n t n = Keyboard . g e t I n t ( ) ;
System . out . p r i n t l n ( “Number i s : ” + n ) ;
}
}
46 65
Compile time error
Checked exceptions must be handled or declared.
Otherwise, they cause compile time errors.
> javac Keybord.java
Keyboard.java:9: unreported exception java.io.IOException;
must be caught or declared to be thrown
System.in.read(buffer);
^
1 error
47 65
import j a v a . i o . ∗ ;
pub l i c c l a s s Keyboard {
pub l i c s t a t i c i n t g e t I n t ( ) throws IOExcept i on {
byte [ ] b u f f e r = new byte [ 2 5 6 ] ;
System . i n . r ead ( b u f f e r ) ; // throws IOExcept i on
S t r i n g s = new S t r i n g ( b u f f e r ) ;
i n t num = I n t e g e r . p a r s e I n t ( s . t r i m ( ) ) ;
r e t u r n num ;
}
pub l i c s t a t i c vo id main ( S t r i n g [ ] a r g s ) {
System . out . p r i n t ( ” P l e a s e e n t e r a number : ” ) ;
i n t n = Keyboard . g e t I n t ( ) ; // throws IOExcept i on
System . out . p r i n t l n ( “Number i s : ” + n ) ;
}
}
48 65
Compile time error
Checked exceptions must be handled or declared.
Otherwise, they cause compile time errors.
> javac Keyboard.java
Keyboard.java:22: unreported java.io.IOException;
must be caught or declared to be thrown
int n = Keyboard.getInt();
^
1 error
49 65
import j a v a . i o . ∗ ;
pub l i c c l a s s Keyboard {
pub l i c s t a t i c i n t g e t I n t ( ) throws IOExcept i on {
byte [ ] b u f f e r = new byte [ 2 5 6 ] ;
System . i n . r ead ( b u f f e r ) ; // throws IOExcept i on
S t r i n g s = new S t r i n g ( b u f f e r ) ;
i n t num = I n t e g e r . p a r s e I n t ( s . t r i m ( ) ) ;
r e t u r n num ;
}
pub l i c s t a t i c vo id main ( S t r i n g [ ] a r g s )
throws IOExcept i on {
System . out . p r i n t ( ” P l e a s e e n t e r a number : ” ) ;
i n t n = Keyboard . g e t I n t ( ) ; // throws IOExcept i on
System . out . p r i n t l n ( “Number i s : ” + n ) ;
}
}
50 65
Declaring an exception
When declaring (throws) an exception without processing it (catch) the method
terminates abruptly when the exception is thrown.
> java Keyboard
Please enter a number: oups
Exception in thread “main” java.lang.NumberFormatException
For input string: “oups”
at java.lang.NumberFormatException.
forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:468)
at java.lang.Integer.parseInt(Integer.java:518)
at Keyboard.getInt(Keyboard.java:13)
at Keyboard.main(Keyboard.java:23)
51 65
import j a v a . i o . ∗ ;
pub l i c c l a s s Keyboard {
pub l i c s t a t i c i n t g e t I n t ( ) throws IOExcept ion {
byte [ ] b u f f e r = new byte [ 2 5 6 ] ;
System . i n . r ead ( b u f f e r ) ;
S t r i n g s = new S t r i n g ( b u f f e r ) ;
i n t num = I n t e g e r . p a r s e I n t ( s . t r im ( ) ) ;
re tu rn num ;
}
// . . .
52 65
// . . .
pub l i c s t a t i c vo id main ( S t r i n g [ ] a r g s ) throws IOExcept i on {
i n t n ;
boolean done = f a l s e ;
wh i l e ( ! done ) {
System . out . p r i n t ( ” P l e a s e e n t e r a number : ” ) ;
t r y {
n = Keyboard . g e t I n t ( ) ;
System . out . p r i n t l n ( “The number i s ” + n ) ;
done = t rue ;
} catch ( NumberFormatException e ) {
System . out . p r i n t l n ( ” Not a number ! ” ) ;
}
}
}
}
53 65
Exemple
This example handles exceptions of type NumberFormatException, but leaves out
exceptions of type IOException.
> java Keyboard
Please enter a number: oups
Not a number!
Please enter a number: a1
Not a number!
Please enter a number: 1
The number is 1
54 65
New types
Theory
Learning objectives:
Creating new types of exceptions.
Readings:
Pages 29–36 of E. Koffman and P. Wolfgang.
55 65
New types
Syntax
How do we create new types of exceptions?
Exceptions are objects.
So all you have to do is create new classes.
The subclasses of the class Exception are at checked.
Unless they are subclasses of the class RuntimeException, then they are at
unchecked.
56 65
Creating new types of exception
pub l i c c l a s s MyException extends Excep t i on {
}
pub l i c c l a s s MyException extends Runt imeExcept ion {
pub l i c MyException ( ) {
super ( ) ;
}
pub l i c MyException ( S t r i n g message ) {
super ( message ) ;
}
}
Why creating new types of exception?
57 65
New types
Example
Example: Time
In the following example, the method parseTime catches exceptions of type
NumberFormatException or NoSuchElementException in order to throw an
exception of a more informative type, TimeFormatException.
pub l i c c l a s s TimeFormatExcept ion extends I l l e g a lA r g umen tE x c e p t i o n {
pub l i c TimeFormatExcept ion ( ) {
super ( ) ;
}
pub l i c TimeFormatExcept ion ( S t r i n g msg ) {
super (msg ) ;
}
}
58 65
Example: Time
pub l i c c l a s s Time {
// . . .
pub l i c s t a t i c Time parseTime ( S t r i n g t i m e S t r i n g ) {
S t r i n g T o k e n i z e r s t ;
s t = new S t r i n g T o k e n i z e r ( t i m e S t r i n g , ” : ” , t rue ) ;
i n t h , m, s ;
t r y {
h = I n t e g e r . p a r s e I n t ( s t . nextToken ( ) ) ;
} catch ( NumberFormatException e1 ) {
throw new TimeFormatExcept ion ( ” not a number : “+t i m e S t r i n g ) ;
} catch ( NoSuchElementExcept ion e2 ) {
throw new TimeFormatExcept ion ( ” s e p a r a t o r not found : “+t i m e S t r i n g ) ;
}
t r y {
s t . nextToken ( ) ;
} catch ( NoSuchElementExcept ion e2 ) {
throw new TimeFormatExcept ion ( ” s e p a r a t o r not found : “+t i m e S t r i n g ) ;
}
59 65
Example: Time
t r y {
m = I n t e g e r . p a r s e I n t ( s t . nextToken ( ) ) ;
} catch ( NumberFormatException e1 ) {
throw new TimeFormatExcept ion ( ” not a number : “+t i m e S t r i n g ) ;
} catch ( NoSuchElementExcept ion e2 ) {
throw new TimeFormatExcept ion ( ” s e p a r a t o r not found : “+t i m e S t r i n g ) ;
}
t r y {
s t . nextToken ( ) ;
} catch ( NoSuchElementExcept ion e2 ) {
throw new TimeFormatExcept ion ( ” s e p a r a t o r not found : “+t i m e S t r i n g ) ;
}
t r y {
s = I n t e g e r . p a r s e I n t ( s t . nextToken ( ) ) ;
} catch ( NumberFormatException e1 ) {
throw new TimeFormatExcept ion ( ” not a number : “+t i m e S t r i n g ) ;
} catch ( NoSuchElementExcept ion e2 ) {
throw new TimeFormatExcept ion ( ” t h i r d f i e l d not found : “+t i m e S t r i n g ) ;
}
60 65
Example: Time
i f ( s t . hasMoreTokens ( ) ) {
throw new TimeFormatExcept ion ( ” i n v a l i d s u f f i x : ” + t i m e S t r i n g ) ;
}
i f ( ( h<0) | | ( h>23) | | (m<0) | | (m>59) | | ( s <0) | | ( s >59) ) {
throw new TimeFormatExcept ion ( ” v a l u e s out o f range : ” + t i m e S t r i n g ) ;
}
r e t u r n new Time ( h ,m, s ) ;
}
}
61 65
Summary
A precondition is a condition that must be met before a method can be executed.
In object-oriented programming, we need to validate not only the parameter values, but
also the state of the object.
In Java, we use the exceptions to report run-time errors.
The try/catch block is used to handle exceptions, i.e. stopping propagation.
62 65
Next module
Abstract Data Type (ADT): queue.
63 65
References I
E. B. Koffman and Wolfgang P. A. T.
Data Structures: Abstraction and Design Using Java.
John Wiley & Sons, 3e edition, 2016.
64 65
Marcel Turcotte
Marcel.
School of Electrical Engineering and Computer Science (EECS)
University of Ottawa
65 / 65
Marcel.
Preamble
Summary
Learning objectives
Plan
Error handling
Introduction
Preconditions
Exception
The class Exception
Variable of type Exception
Object from the class Exception
Throw
Throw statement
Transfer of control
Examples
Try-Catch
Syntax
Example
Flow of control
Comprehensive example
The reference of type Exception
Throws
Mandatory declaration or not
Syntax
Example
New types
Syntax
Example
Prologue