Error Handing PDF
Error Handing PDF
1
2 UNIT 10
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
Program errors and exception handling 3
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
4 UNIT 10
int a, b, x;
a = 5;
b = Integer.parseInt(kb.readLine()); // reading of b
... // statements that do not change b
System.out.println("b = " + b);
x = a/b;
Once the causes for the error have been identified and corrected, the print statements can be removed before
closing the debugging session.
Note: If it is necessary to explore the content of objects, rather than of simple variables of primitive data types,
we can make use of the toString() method, which provides information on the content of the object. We could
also redefine toString() so as to simplify the reading of the state of the object during debugging.
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
Program errors and exception handling 5
at java.lang.Integer.parseInt(Integer.java:518)
at TestException.main(TestException.java:3)
Hence, the string "this println statement is not executed" is not printed.
In Java, the errors that occur at runtime are represented by means of exceptions. Java offers a predefined set
of exceptions that can be thrown during program execution.
To avoid that a program terminates unexpectedly, Java allows us to handle exceptions by means of a suitable
construct.
Throwable
Error Exception
ArrayIndexOutOfBoundException NumberFormatException
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
6 UNIT 10
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
Program errors and exception handling 7
Semantics:
Throws an exception of the type indicated by the object appearing as parameter to the throw statement.
Example:
throw new MyException("message for MyException");
This statement throws an exception of type MyException, which prints on the screen the message that appears
as parameter to the constructor.
10.18 Example
import java.io.*;
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
8 UNIT 10
• try-block : sequence of statements that will be executed under the control of the following catch clauses
• catch-block : sequence of statements that will be executed if a statement in the try-block generates
an exception of the type specified in the corresponding catch clause
• finally-block : sequence of statements that will be always executed (both in the case where the
try-block is executed without exceptions, and in the case where a catch-block is executed to catch an
exception).
Semantics:
Catches one or more exceptions that can occur in a code fragment. The execution of the statements in the
try-block is interrupted in the case where one of these statements generates an exception. If this happens,
the catch clauses are evaluated in the order in which they are written, and the catch-block is executed that
corresponds to the first clause for which the generated exception belongs to the specified class. Finally, the
statements in the finally-block are executed.
If no statement in the try-block generates an exception, then, at the end of its execution, only the statements
in finally-block are executed.
Example:
try {
System.out.println(Integer.parseInt(br.readLine());
}
catch(IOException e1) {
System.out.println("An IO error occurred.");
}
catch(NumberFormatException e2) {
System.out.println("The string read does not contain an integer.");
}
finally {
System.out.println("Block executed.");
}
This code fragment tries to convert a string read from an input channel to an integer and to print the integer.
If an IO error occurs, or if the string read does not contain a sequence of digits, a corresponding error message
is printed on the video. In any case, the println() statement for the string "Block executed", corresponding
to the finally clause, is executed.
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
Program errors and exception handling 9
import java.io.*;
import java.io.*;
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
10 UNIT 10
catch (NumberFormatException e) {
System.out.println("The file contains non numeric data.");
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
If the file contains alphanumeric data that cannot be converted to integer values, the first program would
generate the following error message:
Exception in thread "main" java.lang.NumberFormatException: For input string: "pippo"
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 MaximumWithoutExceptions.main(MaximumWithoutExceptions.java:12)
The second program, instead, would handle the exception and print:
The file contains non numeric data.
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
Program errors and exception handling 11
Note that, in order to allow the chain of terminations started by the second() method to propagate to the
main() method, it is necessary that all methods that are part of the termination chain have in their header the
throws clause with the list of involved exceptions: in this case, only Exception.
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
12 UNIT 10
int n = Integer.parseInt(line);
System.out.println(n);
}
catch(NumberFormatException e) {
System.out.println("***");
}
line = in.readLine();
}
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
Exercises
Exercise 10.1. Determine whether the following program will generate (i) compilation errors, (ii) runtime
errors. If the program does not generate errors, say what it will print out; if the program generates errors,
correct them and say what it will print out after the correction. Motivate your answers.
public class Exercise1 {
public static void main(String[] args) {
for (int i = 0, j = 0; i < 10, j < 10; i++, j++) {
System.out.println(i + " + " + j + " = " + (i+j));
}
System.out.println("I’ve printed out the sums of i and j up to "
+ i + "," + j);
}
}
Exercise 10.2. Determine whether the following program will generate (i) compilation errors, (ii) runtime
errors. If the program does not generate errors, say what it will print out; if the program generates errors,
correct them and say what it will print out after the correction. Motivate your answers.
public class Exercise2 {
Exercise 10.3. Determine whether the following classes will generate (i) compilation errors, (ii) runtime
errors. If the program does not generate errors, say what it will print out; if the program generates errors,
correct them and say what it will print out after the correction. Motivate your answers.
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
Program errors and exception handling 13
Exercise 10.4. Capture all exceptions in the following program, printing out error messages that describe
the type of error that occurred.
import java.io.*;
Exercise 10.5. Solve Exercise 9.6 by handling explicitly all exceptions by printing out suitable error messages.
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07
14 UNIT 10
Exercise 10.6. Define a new exception, called ExceptionLineTooLong, that prints out the error message
"The strings is too long". Write a program that reads all lines of a file and throws an exception of type
ExceptionLineTooLong in the case where a string of the file is longer than 80 characters. Handle also all
exceptions that could be thrown by the program.
Exercise 10.8. Define the exceptions that are necessary to catch the possible errors that can occur in the
class Matrix of Exercise 9.9.
• ExceptionWrongMatrixValues that is thrown in the method read() if the data on the file does not
correspond to numeric values, or if the data are not consistent with the form of a matrix (e.g., the rows
have different length);
• ExceptionWrongMatrixDimension that is thrown in the method read() if the data on the file do not
correspond to the dimension of the matrix.
Modify the class Matrix in such a way that it generates the new exceptions when necessary.
Diego
c Calvanese Lecture Notes for Introduction to Programming A.A. 2006/07