0% found this document useful (0 votes)
4 views55 pages

C209 6P P05 Session1

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 55

School of Infocomm

C209
ADVANCED OBJECT-ORIENTED PROGRAMMING
PROBLEM 05
SESSION 1
Sushi World
EXCEPTIONS

2
What is an Exception?
 Definition
 An exception is an event, which occurs during the
execution of a program, that disrupts the normal flow
of the program's instructions.

 When an error occurs within a method, the method


creates an object and hands it off to the runtime
system.

 The object, called an exception object, contains


information about the error, including its type and
the state of the program when the error occurred.

P05 Sushi World 3


Throwing an Exception
 Creating an exception object and handing it to the
runtime system is called throwing an exception.

 After a method throws an exception, we need to


handle it properly, otherwise the program will
terminate abnormally.

P05 Sushi World 4


Abnormal situations
 Scenarios
 When running a Java program, several things can go wrong:
 Attempting to divide by 0.
 Accessing an array index that is out of bounds.
 Invalid data format or type.
 Accessing files that cannot be found.

 These types of abnormal situations are known as exceptions in


Java.

 If a program does not handle these exceptions, the program


abnormally terminates.

Unhandled
exception
P05 Sushi World 5
Handling Exceptions
 In Java, to handle exceptions, we use the try-catch
block to help us:
try
{
// some code that may cause an error
// (throw an exception)

}
catch(<ExceptionType> <nameOfException>)
{
// some code to respond to the error
// (Handle the exception)

}

P05 Sushi World 6


Handling Exceptions
Using the try-catch statement try block:
Contains statements that
int result = 0;
may throw exceptions.
try {
result = 3 / 0; Throw!
System.out.println("Did we reach here?");
} // end try
ArithmeticException

catch (ArithmeticException ae) { Catch!


System.out.println("Error! Cannot divide by 0");
ae.printStackTrace();
} // end catch catch block:
Specifies what type of
System.out.println("Result is " + result); exception to deal with
printStackTrace() tells you what happened and where in the (ArithmeticException).
code the error happened. This is similar to what you see in an
abnormal termination if no try-catch is used.
Specifies how to deal with
the exception.
The stack trace is useful only to the developer of the code. Usually we
will print something more readable for the user such as “Error!
P05 Sushi World Cannot divide by 0” WITHOUT the stack trace. 7
Some types of runtime exceptions
Runtime Exception Code Snippets
String s = null;
NullPointerException System.out.println(s.length());

int a = 3, b = 0;
ArithmeticException int q = a / b;

int [] a = new int[10];


ArrayIndexOutOfBoundsException System.out.println(a[10]);

System.out.println(Integer.parseInt("ten"));
NumberFormatException

String s = "Hello";
StringIndexOutOfBoundsException System.out.println(s.charAt(5));

Why would the code snippets above throw exceptions?


Note:
The examples shown here are to demonstrate the circumstances that an exception may be thrown.
P05 Sushi World 8
Exception Class Hierarchy
ArrayIndexOutOfBoundsException
Throwable
ArithmeticException

Exception ClassCastException

IOException NullPointerException

… NumberFormatException

RuntimeException StringIndexOutOfBoundsException


P05 Sushi World 9
Exercise
 Open ArithmeticExceptionExample.java
a) Which line of code in ArithmeticExceptionExample
caused the error highlighted below? What is the
reason?

b) What is another way to write the code without using


try-catch?

P05 Sushi World 10


Exercise - Solution
 Open ArithmeticExceptionExample.java

 Which line of code in ArithmeticExceptionExample


caused the error highlighted below? What is the
reason?
 Line 12 caused the error as the denominator entered was 0.
Attempting to divide by 0 is an abnormal situation, and will
cause an error to be thrown.

P05 Sushi World 11


Exercise - Solution
 Another way to write the code without using try-
catch:

P05 Sushi World 12


Exercise
 Open NullPointerExceptionExample.java
 Study the table and fill in the blanks below based on the code in
NullPointerExceptionExample. The first one is done for you.

 Examine NullPointerExceptionExample. Are there any errors in


NullPointerExceptionExample.java?

 Execute NullPointerExceptionExample.java

 What is the output? Why do you think this output is shown?

P05 Sushi World 13


Exercise - solution
 nameArray

 There are no syntax errors in the code. However, as the loop attempts
to perform an operation on every single element in the array, when it
hits a null, an error will be thrown.

 The error below is thrown as there was an attempt to convert the


values in the array to uppercase. You cannot perform operations
on a null. Type of exception

Which null caused


the error?

P05 Sushi World File name and line number of the code where the error ocurred. 14
Exercise
 Modify the code in NullPointerExceptionExample so that it looks
like the below:

Customise the message

 Execute NullPointerException again. What is the output now?

 What is another way to write the code without using try-catch?

 We used an array in our NullPointerException exercise – can we


use an ArrayList instead? Why or Why not?
P05 Sushi World 15
Exercise - solution
 You should now see the following output.
Observe that the error is now handled, and the
program does not terminate abnormally.

P05 Sushi World 16


Exercise - solution
 Another way to write the code without try-catch

 No, ArrayList is dynamic. Hence NullPointerException


will not be encountered due to null elements in the
ArrayList.
P05 Sushi World 17
Exercise
 Open IndexOutOfBoundsExample.java and execute
the file.
a) What is the output? Why do you think this output is
shown?
b) Using try-catch, modify the code so that you get the
following output.

c) We used an array in the above exercise – can the


IndexOutOfBoundsException occur to an ArrayList?

P05 Sushi World 18


Exercise - solution
 What is the output? Why do you think this output is
shown?
 The size of nameArray is 10, so the largest possible
index is 9. However, there is a line in the code where a
String is assigned to nameArray at index 10, which does
not exist.

P05 Sushi World 19


Exercise - solution
 Using try-catch, modify the code in
IndexOutOfBoundsExample.java so that you get the
following output.

 Yes, IndexOutOfBoundsException can happen for


ArrayList, e.g. when using get() with an index that is
larger than the ArrayList size.
P05 Sushi World 20
Exercise
 Open NumberFormatTest.java and execute the
code.
 In NumberFormatTest, we use the readInt method to
prompt the user to enter a number.
 If we enter alphabets, we will be informed to enter an integer
instead until we input a number.

 You should see the following output:

P05 Sushi World 21


Exercise
 Open Helper.java and look for the readInt method.

 Comment out the code in Helper.java as shown.

 Save Helper.java
 Execute NumberFormatTest.java again. What is the
output? Explain why this happened.
P05 Sushi World 22
Exercise - solution
 The try-catch was there to help handle number
format exceptions such as when the user enters an
alphabet.

If we remove the try-catch, such non-number inputs


are no longer handled, hence the program will
terminate abnormally.
An attempt to convert a
string to one of the
numeric types(in the
readInt() case, an integer),
but the conversion was
unsuccessful.

P05 Sushi World 23


Exercise - solution
 IMPORTANT:
 Undo the commenting you did in part d) above in
Helper.java.

 Save Helper.java

P05 Sushi World 24


When to use exceptions, try-catch
 If the error is something that you can easily check,
you shouldn't use exceptions.

 Some of the examples covered earlier for learning


about exception handling, can be checked using
simple conditional statements.

 Use exception handling when


 You have already done all the necessary checks, but
still feel there may be some other unexpected errors.
 The Java class that you are using requires it.
 E.g. Classes required to read files, and write to files

P05 Sushi World 25


FILE READ

26
Simple file reading
 Related classes to read information from a file
 File
 To create a new File instance from a file path.

 FileReader
 To read from the specified file.
 Reads streams of characters.

 BufferedReader
 To read text from a character-input stream.
 Buffers characters so as to provide for the efficient reading of characters,
arrays, and lines.

 try…catch is needed for File I/O


 IOException
 General class of exceptions for file input/output
 FileNotFoundException
 File not found during file reading

P05 Sushi World 27


File Read steps
 File reading involves the following operations:
1. Open the file
2. Read from the file
3. Close the file

P05 Sushi World 28


Performing File I/O - Reading
 Reading the content of a file – data.txt
try {
File file = new File("data.txt");
FileReader fr = new FileReader(file); Opens the file
BufferedReader br = new BufferedReader(fr);

String line = br.readLine();


while (line != null) {
System.out.println(line); Reads from the file
line = br.readLine();
}
Closes the file
br.close();

} catch (FileNotFoundException e) {
Try/catch guards
e.printStackTrace();
against non-existent
} catch (IOException io) {
file opening
io.printStackTrace();
}
P05 Sushi World 29
Performing File I/O - Reading
 We can also combine the lines to prepare the file,
into a single line. This is seen in some tutorials online
File file = new File("data.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);

Combine the 3 lines above into 1 line below

BufferedReader br = new BufferedReader(new FileReader(new File("data.txt")));

P05 Sushi World 30


Exercise
 Open and execute FileReadExample.
 What is the output? What may have caused the error?
Fix the code.

P05 Sushi World 31


Exercise - solution
 What is the output? What may have caused the
error? Fix the code.

The file could not be found as


the file extension is missing.
Change “data” to “data.txt”

P05 Sushi World 32


FILE WRITE

33
File writing
 Related classes to write information to a file
 File
 To create a new File instance from a file path.

 FileWriter
 To write to the specified file.
 If the file does not exist yet, the file will be created.
 If the file already exists, we can either overwrite the file, or append to the file.
 Reads streams of characters.

 BufferedWriter
 To write text to a character-output stream
 Buffers characters so as to provide for the efficient writing of single characters,
arrays, and strings.

 try…catch is needed for File I/O


 IOException
 General class of exceptions for file input/output

P06 Text Editor 34


Performing File I/O – Writing
 Writing 2 lines of text to a file: output.txt
try {
File file = new File("output.txt");
FileWriter fw = new FileWriter(file); Opens the file
BufferedWriter bw = new BufferedWriter(fw);

bw.write("This is line 1");


Writes to the file
bw.write("This is line 2");

bw.close(); Closes the file

} catch (IOException io) {


io.printStackTrace();
}

Try/catch guards
against error on file
operations

P06 Text Editor 35


Performing File I/O – Writing, append
 Append 2 lines of text to a file: output.txt
try {
File file = new File("output.txt");
FileWriter fw = new FileWriter(file, true); Opens the file
BufferedWriter bw = new BufferedWriter(fw);

bw.write("This is line 3");


Writes to the file
bw.write("This is line 4");

bw.close(); Closes the file

} catch (IOException io) {


io.printStackTrace();
}

Try/catch guards
against error on file
operations

P06 Text Editor 36


Exercise
 Execute FileWriteExample.java.
 Refresh the project package P05. You should see
“output.txt” appear.

 Note: In Eclipse's Package Explorer, you must click on P05


project and press [F5] (Or right-click on the project folder and
click Refresh.) after performing Save Document in order to see
the generated text file, <filename>.txt

 Open output.txt, what is in this file?


P06 Text Editor 37
Exercise - solution

P06 Text Editor 38


Exercise
 Modify the following lines in FileWriteExample as
shown:
 Change these lines of code:
 bw.write("This is line 1\n");
 bw.write("This is line 2\n");

to:
 bw.write("This is line 3\n");
 bw.write("This is line 4\n");

 Execute FileWriteExample, what is in output.txt now?


What happened?

P05 Sushi World 39


Solution
 output.txt got overwritten with the new content.

P05 Sushi World 40


Exercise
 Modify FileWriteExample as shown:

What do you think


true here means?

 Execute FileWriteExample. What is in output.txt now?

 Explain what happened.

P05 Sushi World 41


Solution
 The content in output.txt is now:

 Instead of overwriting the file, the program now appends


to the end of the last line of the file.

 The true in the FileWriter constructor indicates that the


file should append the new content.
 If not indicated, the default is false, that is to overwrite the
original content.
P05 Sushi World 42
File write steps
 File write involves the following operations, similar to
file reading:
 Opens the file
 Write\Append to the file
 Closes the file

P06 Text Editor 43


CONVERSION

44
Convert String to Numbers, Numbers to String
 Whenever we read data from a text file, the information
is typically read as a String value.

 However there are times when the data being read is


supposed to be in a numeric format.
 E.g. price, gpa, height, etc

 In such cases, we need to convert the String value to a


numeric value so that the information can be useful.

 Sometimes you may also need to convert a number to a


string because you need to operate on the value in its
string form.
P05 Sushi World 45
Integer class
 The Integer class wraps a value of the primitive type
int in an object.

 In addition, this class provides several methods for


converting an int to a String and a String to an int, as
well as other methods useful when dealing with an
int. Notice that these are static methods,
similar to how we use Helper class.
 Integer.parseInt(String s) E.g. Helper.readInt(…)

 Returns the integer value represented by the argument.


 Integer.toString(int i)
 Returns a String object represented by the argument.

P05 Sushi World *Refer to C209 P01 46


Double class
 The Double class wraps a value of the primitive
type double in an object.

 In addition, this class provides several methods for


converting a double to a String and a String to
a double, as well as other constants and methods
useful when dealing with a double.
 Double.parseDouble(String s)
 Returns the double value represented by the argument.
 Double.toString(double d)
 Returns a String object represented by the argument.

P05 Sushi World 47


Converting Numbers to Strings
 Other easy ways to convert a number to a string:

int x = 10;

// Concatenate “x” with an empty string;


// Conversion is handled for you.
String s1 = "" + x;

Or

// The valueOf class method.


String s2 = String.valueOf(x);

P05 Sushi World 48


Exercise
 Fill in the blanks to perform the correct conversion.

P05 Sushi World 49


Solution

What type of exception do you think will be thrown for the last instruction?

P05 Sushi World 50


Exercise
 Study the FoodDemo class.

 The expected output for FoodDemo is:

 Run and execute the FoodDemo class.


 What is the output? Why?

P05 Sushi World 51


Solution
 The following error occurred:

 The error occurred because foodInfo[1] is a String


value, but a double value was expected.

P05 Sushi World 52


Exercise
 What do you need to modify in order for the program
to execute correctly?

 Fix the issue and test your program again.

P05 Sushi World 53


Solution
 What do you need to modify in order for the program
to execute correctly?
 Use the parseDouble from the Double class to convert
the String value to a double value.

 Fix the issue and test your program again.


output +=
String.format("%-15s%-10.2f\n",
foodInfo[0],
Double.parseDouble(foodInfo[1]));

P05 Sushi World 54


Summary
 What you have learned
 Explain exceptions as an event that disrupts the normal
flow of a programs execution
 Identify the different types of exceptions
 Explain how exceptions are handled namely how
exceptions are thrown and how they are caught
 Implement exception handling
 Explain and implement file reading and file writing
 Convert a String to a numeric value and converting a
numeric value to a String.

P05 Sushi World 55

You might also like