Chapter Three Revised
Chapter Three Revised
Chapter 3
Exception Handling and Files IO Streams
What is an exception?
An exception is an error that occurs during the execution of a program. The exception handling
in java is one of the powerful mechanisms to handle the runtime errors so that normal flow of
the application can be maintained. Java facilitates the management of such errors by diverting
control to special program bocks that are called exception handlers.
Exception handling enables programmers to create applications that can resolve (or handle)
exceptions. In many cases, handling an exception allows a program to continue executing as if
no problem had been encountered. These features enable programmers to write robust and fault-
tolerant programs.
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code.
It means we can't use try block alone.
The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception.
It must be preceded by try block which means we can't use catch block alone.
It can be followed by finally block later.
1|Page
Exception Handling and File IO Stream
catch(ArithmeticException e)
{ // resolving the exception in catch block
System.out.println(i/(j+2));
System.out.println(e);
} }}
Example :- Scenario where ArrayIndexOutOfBoundsException occurs
package testexce;
public class TestEXce {
public static void main(String[] args) {
int[] ar={5,4,8,6};
int i=0;
try{
for(i=4;i>=0;i--)
System.out.println("Array ["+i+"] = "+ar[i]);
}
catch(Exception e){
System.out.println("Array ["+i+"] = "+8);
System.out.println(e);
}}}
Example:- on throw keyword.
public class TestThrow1{
static void validate(int age)
{ if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote"); }
public static void main(String args[]){
validate(13);
System.out.println("rest of the code..."); } }
Java throws keyword
The Java throws keyword is used to declare an exception.
It gives information to the programmer that there may occur an exception so it is
better for the programmer to provide the exception handling code so that normal
flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions.
If there occurs any unchecked exception such as Null PointerException, it is
programmers fault that he is not performing checkup before the code being used
3|Page
Exception Handling and File IO Stream
OutputStream Hierarchy
The structure of outputstream classes in java can be summarized as in the diagram below.
2. InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes. There are some useful methods to use a file as an input terminal in java program.
The methods are described in table below. Useful methods of InputStream
Method Description
1) public abstract int read()throws reads the next byte of data from the input stream. It
IOException returns -1 at the end of the file.
2) public int available()throws returns an estimate of the number of bytes that can be
IOException read from the current input stream.
3) public void close()throws is used to close the current input stream.
IOException
5|Page
Exception Handling and File IO Stream
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to java file.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}
catch(Exception e){
System.out.println(e);}
} }
In the above program, the content of a text file testout.txt is set with the data Welcome to java
file. in the D directory.
Java FileInputStream example
package com.javatpoint;
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i); }
fin.close();
} catch(Exception e){
System.out.println(e);}
} }
In the above program, the content of a text file testout.txt is read and the data Welcome to java
file. will be displayed to the console.
java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to "mark" Java
classes so that the objects of these classes may get a certain capability. It must be implemented
by the class whose object you want to persist/save to a file.
ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types, and Java objects to an
OutputStream. Only objects that support the java.io.Serializable interface can be written to
streams.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the
methods for serializing and deserializing an object. The ObjectOutputStream class contains
many write methods for writing various data types, but one method in particular stands out.
6|Page
Exception Handling and File IO Stream
Constructor
Important Methods
Method Description
1) public final void writeObject(Object obj) writes the specified object to the
throws IOException {} ObjectOutputStream.
2) public void flush() throws IOException {} flushes the current output stream.
3) public void close() throws IOException {} closes the current output stream.
ObjectInputStream class
An ObjectInputStream deserializes objects and primitive data written using an
ObjectOutputStream.
Constructor
1) public ObjectInputStream(InputStream in) creates an ObjectInputStream that reads
throws IOException {} from the specified InputStream.
Important Methods
Method Description
1) public final Object readObject() throws IOException, reads an object from the input
ClassNotFoundException{} stream.
2) public void close() throws IOException {} closes ObjectInputStream.
The above method serializes an Object and sends it to the output stream. Similarly, the
ObjectInputStream class contains the following method for deserializing an object
This method retrieves the next Object out of the stream and deserializes it. The return value is
Object, so you will need to cast it to its appropriate data type.
Serializing an Object
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.
7|Page
Exception Handling and File IO Stream
this.name = name; } }
class Persist{
public static void main(String args[]){
try{
//Creating the object
Student s1 =new Student(211,"ravi");
//Creating stream and writing the object
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
//closing the stream
out.close();
System.out.println("success serialization");
}catch(Exception e){System.out.println(e);}
}
}
Deserializing an Object
Deserialization is the process of reconstructing the object from the serialized state. It is the
reverse operation of serialization. Let's see an example where we are reading the data from a
deserialized object. The following DeserializeDemo program deserializes the Employee object
created in the SerializeDemo program. Study the program and try to determine its output
Example 1.
import java.io.*;
class Employee implements Serializable {
String name;
String address;
int SSN;
int number;}
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number); }}
Example2.
import java.io.*;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name; } }
class Depersist{
public static void main(String args[]){
try{
//Creating stream to read the object
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject(); //printing the data of the serialized object
System.out.println(s.id+" "+s.name);
//closing the stream
in.close();
}catch(Exception e){System.out.println(e);}
}
}
The output.
211 ravi
Here are following important points to be noted in the example1 above.
The try/catch block tries to catch a ClassNotFoundException, which is declared by the
readObject() method. For a JVM to be able to deserialize an object, it must be able to find
the bytecode for the class. If the JVM can't find a class during the deserialization of an
object, it throws a ClassNotFoundException.
Notice that the return value of readObject() is cast to an Employee reference.
10 | P a g e
Exception Handling and File IO Stream
The value of the SSN field was 11122333 when the object was serialized, but because the
field is transient, this value was not sent to the output stream. The SSN field of the
deserialized Employee object is 0.
Stream Tokenizers
You can write an auxiliary method that decomposes a string into its tokens, but this task arises in
a specific case. Java language designers have devised a helper class, classStringTokenizer
(found in the package, java.util), that contains methods for de-composing strings into tokens.
Strings = "$13.46";
StringTokenizer t = new StringTokenizer(s,"$.");
String dollars= t.nextToken();
String cents= t.nextToken();
The second statement creates a string tokenizer that considers both $and. to be legal delimiters
.A string tokenizer can use multiple distinct delimiters, and the delimiters are packaged as a
string to the tokenizer's constructor method.
To keep things simple, we will work with text files and how to read and write streams of data
into them. Because Java does not impose any structure while manipulating sequential access to a
file, so, it is the responsibility of the programmer to establish a structure, meaning, how the data
will be stored in the file. Therefore, the programmer must structure files for instance into rows
and columns to meet the requirements of a specific application. The Formatter class of
java.util.Formatter package can support Sequential Access Text file as in example below.
package fileformatter;
import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class FileFormatter {
private static Formatter output; // outputs text to a file
public static void main(String[] args) {
// TODO code application logic here
openFile();
addRecords();
closeFile();
}
// open file clients.txt
public static void openFile()
{ try
{
output = new Formatter("D:\\clients.txt"); // open the file }
catch (SecurityException securityException)
{
System.err.println("Write permission denied. Terminating.");
11 | P a g e
Exception Handling and File IO Stream
12 | P a g e