Object Oriented Programming Java 1 - Lecture 11
Object Oriented Programming Java 1 - Lecture 11
Lecture 11
Exception Handling
Learning Outcomes
The Error class as shown in Figure 1 represents serious errors that usually pose a challenge
that makes the program unable to recover [1]. Such Error conditions include scenarios where
a program runs out of memory and cases where a program fails to locate required files [1].
On the other hand, the Exception class represents less serious errors that occurs as unusual
conditions [1]. Fortunately, a program is normally able to recover from such types of errors.
The most common examples include arithmetic exceptions, array index out of bound
exceptions, no such element exceptions, and input mismatch exceptions.
Consider the Java program in Figure 2 that prompt for input of two integers, stored in
variables x and y. The program then divides x by y with the results stored in variable z.
The program builds and runs successfully given two integer values for x and y as shown in the
output window. The program is however susceptible to two kinds of exceptions that my cause
it to terminate unexpectedly. These are the input mismatch exception and the arithmetic
exception.
Based on the output window, the program terminated unexpectedly since the user entered
he String “john” instead of an integer value. The main error message says that “Exception in
thread main java.util.InputMismatchException”. This is a clear indicator that an input
mismatch exception was detected causing the program to terminate unexpectedly. The same
is bound to happen if a non-integer value is supplied following a prompt for value y.
b) Arithmetic Exception
This kind of exception is bound to occur in cases where the user inputs a zero (0) for the
prompt for value y. This is based on the fact that any given value cannot be divided by a zero
(0), hence, the expected data types for y should be an integer that is not a zero (0). Figure 4
show what happens when a zero (0) is inputted as the value for variable y.
Figure 3. Input Mismatch Exception Example
Based on the output window, the program terminated unexpectedly since the user entered a
zero (0) following a prompt for y. The main error message says that “Exception in thread main
java.lang.ArithmeticException”. This is a clear indicator that an arithmetic exception was
detected, in this case, an attempt to divide by a zero (0), causing the program to terminate
unexpectedly.
Programmers may opt to ignore exceptions by letting the offending program to terminate
whenever they run into exception conditions. However, doing so may turn out to be abrupt
and unforgiving [1] to program users. There are two ways to handle exceptions
1. Using a decision-making statement to avoid occurrence of errors
2. Using the standard object-oriented exception handling technique
In as much as the if … else decision-making approach may be used to avoid occurrence of
exceptions, it is a very crude way of handling exceptions. The standard exception handling
technique provide a more elegant approach for handling error conditions [1]. This is since
they are deemed to be more fault tolerant and robust [1]. The try … catch … finally blocks are
used in this case, which entails trying pieces of code followed by catching resulting exceptions.
The following is the syntax for the try … catch … finally blocks as applied to exception handling.
try{
//statements likely to cause exceptions
}catch(ExceptionClassName1 objectreference1){
//code to handle the detected exception
}catch(ExceptionClassName2 objectreference2){
//code to handle the detected exception
}catch(ExceptionClassNameN objectreferenceN){
//code to handle the detected exception
}finally{
//statements to execute afterwards
}
The try block contains statements of program code that might generate an exception [2]. In
addition, statements that should not execute in case an exception occurs may also be placed
in the try block. The try block is followed by zero or more catch blocks each of which specifies
the type of exception it is targeting to catch and contains pieces of code for handling the
exception [2]. The finally block may optionally follow the last catch block, in which case, it
contains statements that always execute regardless of whether an exception occurs or not
[2]. However, in cases when a program exits early from a try block by calling the System.exit,
statements placed in the finally block will not execute in this case.
Considering the program example in Figure 2, statements represented by lines 11 and 13 are
likely to cause input mismatch exceptions while line 15 is likely to cause an arithmetic
exception. Thus, to handle the two kinds of exceptions, the statements must be placed in the
try block. Two catch blocks should then be used, each targeting to handle the two exceptions
separately. Hence, Figure 4 show the full program, this time round, exceptions handled
appropriately.
Figure 4. Program with Input Mismatch Exception Handled
According to Figure 4, the try block contains statements of the code that are likely to cause
exceptions. These are the two statements allowing console inputs for two integers to be
stored in variables x and y, and the statements that divides x by y while storing the results in
variable z. The two catch blocks in lines 17 to 21 are independently handling each of the two
exceptions detected and thrown by the try block. Based on the output results, an attempt to
enter String “john” for the value x prompt is detected and caught by the catch block. Notice
that this time round the program does not terminate unexpectedly, it instead notifies the user
about the expected value. The same will happen for a similar violation for value y. In the same
manner, Figure 5 shows the output for an attempt to divide by a zero (0) which is flagged as
an arithmetic exception with the user notified about the occurrence.
Figure 5. Program with Arithmetic Exception Handled
Figure 6 and 7 shows the fact that inclusion of the finally block does not really change anything
in program execution. Instead, the statements located in the finally block are executed
whether the try block detects an exception or not.
Figure 6. Finally Block with no Exception Detected
Summary
The topic has discussed a useful concept of exception handling by first describing exceptions
as unusual occurrences during the point when a program is running. Differences between the
Java Exception class and Error class have been outlines with example given in each case. The
try … catch … finally blocks have been discussed and demonstrated as applied in object-
oriented programming for exception handling. Occurrence of the input mismatch exception
and the arithmetic exception has been demonstrated with the mechanism used to handle
each of them discussed and demonstrated appropriately. A similar approach is applicable for
any other type of exception not demonstrated in this topic. The next topic will demonstrate
another approach that could be used to handle exceptions with a focus on situations where
a computer file being referenced may not be found.
Check Points
Core Textbooks
1. Joyce Farrell, Java Programming, 7th Edition. Course Technology, Cengage Learning, 2014,
ISBN-13 978-1-285-08195-3.
2. Malik, Davender S. JavaTM Programming: From Problem Analysis to Program Design,
International Edition, 5th Edition, Cengage Learning.
Other Resources
References
[1] Farrell, J., Java Programming, 7th Edition. Course Technology, Cengage Learning, 2014,
ISBN-13 978-1-285-08195-3.
[2] Malik, D. S., JavaTM Programming: From Problem Analysis to Program Design,
International Edition, 5th Edition, Cengage Learning.
[3] Sebester, R. W., Concepts of Programming Languages, 12th Edition, Pearson, 2018, ISBN
0-321-49362-1.