COMP 295 JAVA Programming
Fall 2016
FORMAN CHRISTIAN COLLEGE (A Chartered University)
COMP 295Java Programming
Fall 2016
Section: A
Instructor: Tahir Javaid
Lab 10
1) Exception Handling:
Exceptions are some anomalies (error) that happens in program.
e.g.: Accessing array’s 11th element if array’s size is 10.
We can handle exception in two ways:
1) Throw Exception
By throwing exception, we are not concerned with exceptions rather we just throw it to the
calling function.
Syntax:
public void methodThatThrowsException(args) throwsExceptionType
{ …. }
2) Catch Exception
You associate exception handlers with a try block by providing one or more catch blocks
directly after the try block. No code can be between the end of the try block and the beginning of
the first catch block.
Syntax:
try
{
…
}
catch(ExceptionType name)
{
…
}
catch(ExceptionType name)
{
…
}
Each catch block is an exception handler that handles the type of exception indicated by its
argument. The argument type, ExceptionType, declares the type of exception that the handler can
handle and must be the name of a class that inherits from the Throwable class. The handler can
refer to the exception with name.
The catch block contains code that is executed if and when the exception handler is invoked.
The runtime system invokes the exception handler when the handler is the first one in the call
1
COMP 295 JAVA Programming
Fall 2016
stack whose ExceptionType matches the type of the exception thrown. The system considers it a
match if the thrown object can legally be assigned to the exception handler's argument.
The following are two exception handlers for a method that stores elements in an array:
try
{
Array[x]=10;
}
catch(IndexOutOfBoundsException e)
{
System.err.println("IndexOutOfBoundsException: " + e.getMessage());
}
catch(IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
Exception handlers can do more than just print error messages or halt the program. They
can do error recovery, prompt the user to make a decision, or propagate the error up to a higher-
level handler using chained exceptions, as described in the Chained Exceptions section.
2) Java.IO:
Java provides an interface to read and write data from a text file.
Following sample program is to read a line(String) and to write a line(String) on text file.
Syntax:
import java.io.*; // Import library
publicclassInputOutputFile
{
publicstaticvoid main(String[] args)
{
// Reading file throws IOException that is required to be handled...
try
{
FileReader f=newFileReader("hello1.txt"); // Create Low
level input stream
BufferedReader file=newBufferedReader(f);// Create High
Level input Stream from low level input stream
String s1=file.readLine(); // Read a line from text file
file.close(); // close file after reading
}
catch(IOException e)
{
e.printStackTrace();
}
// Writing on file throws IOException that is required to be handled...
try
2
COMP 295 JAVA Programming
Fall 2016
{
FileWriter f=newFileWriter("hello2.txt",true); // Low
level output stream
PrintWriter file=newPrintWriter(f); // High level output
stream from low level output stream
file.println("Empty File"); // write a line in file
file.close(); // close file
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Note:The Boolean value passed to the constructor while making low level output stream tells
whether to make new file if the file does not exists.
IO action throws FileNotFoundExceptionthat is needed to be caught.
Activity 1:Make a file and stores a list of names of 10 fruits in it (one name in
each line). Make a Java program that reads the name of fruits,
sorts them and display it on console.
Activity 2:Make file that stores name and marks of 5 students as follows
(student name, test1, test2, test3). Make a Java program that
reads data. Calculates average test marks and display average of
each student against his/her name. Store name and average marks
of each student in a file “studentsAverage.txt”
3) Java Serialization:
Java provides a mechanism, called object serialization where an object can be represented as
a sequence of bytes that includes the object's data as well as information about the object's type
and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and
deserialized that is, the type information and bytes that represent the object and its data can be
used to recreate the object in memory.
Deserializing objects throws ClassNotFoundException that is required to be caught.
Classes ObjectInputStream and ObjectOutputStream are high- level streams that contain
the methods for serializing and deserializing an object.
3
COMP 295 JAVA Programming
Fall 2016
Notice that for a class to be serialized successfully, two conditions must be met:
The class must implement the Serializable interface.
All of the fields in the class must be Serializable.
Syntax for Serializing Object:
import java.io.*; // import library
publicclassSerializeDemo{
publicstaticvoid main(String[]args){
Employee e =newEmployee(name, address);
Try{
// creating low level stream to serialize objects.
FileOutputStreamfileOut= newFileOutputStream("/tmp/employee.ser");
// creating high level stream from low level stream.
ObjectOutputStreamout=newObjectOutputStream(fileOut);
// serializing object
out.writeObject(e);
// close high level stream.
out.close();
// close low level stream.
fileOut.close();
}catch(IOExceptioni){
i.printStackTrace();
}
}
}
Syntax for Deserializing Object:
import java.io.*; // import library
publicclassDeserializeDemo{
publicstaticvoid main(String[]args){
Employee e;
try
{
// create low level input stream for serialization.
FileInputStreamfileIn=newFileInputStream("/tmp/employee.ser");
// create high level input stream from low level stream.
ObjectInputStreamin=newObjectInputStream(fileIn);
// deserialize object
e =(Employee)in.readObject();
// close high level stream.
in.close();
// close low level stream.
fileIn.close();
}catch(IOExceptioni){
i.printStackTrace();
}catch(ClassNotFoundException c){
System.out.println("Employee class not found");
c.printStackTrace();
}
}
}
4
COMP 295 JAVA Programming
Fall 2016
Activity 3:Create an instance of FullTimeEmployee and PartTimeEmployee
class that you made in Lab 6 (Inheritance). Serialize them.
Activity 4:Deserialize both instances that are serialized in Activity 3 and place
them in Employee class reference. Display their salary.
All The Best
5