Lab 4 Exception Handling and Java Filing
Lab 4 Exception Handling and Java Filing
Lab-04
Exception Handling and Java Filing
Table of Contents
1. Introduction 38
3. Concept Map 39
3.1. Throw Clause 39
3.2. Throws Clause 39
3.3. king input in Java 39
5. Practice Task 43
5.1. Practice Task 1 43
5.2. Practice Task 2 43
5.3. Practice Task 3 43
5.4. Out comes 43
5.5. Testing 44
6. Further Reading 44
6.1. Books 44
6.2. Slides 44
6.3. File Modes in Java 44
Page 37
Lab4: Exception Handling and Java Filing
1. Introduction
This lab is a continuation of the last lab. In your last lab you have learnt the basics of
exception handling. You have understood the hierarchy of the built-in classes used in Java
for exception handling. In this lab, you will learn how to create your own customized
exceptions.
Java has not provided the classes that cover each and every exceptional scenario but they
have formulated a way by which we can write our own exception classes and integrate in
our projects. For example, consider we are implementing a banking application which deals
with all aspects of the bank. For banks there are some scenarios for which they generate
warnings to the clients like if the balance is less than 5000 rupees then the bank gives a
balance critical warning. In programming we can check this using if else statements but,
using exception handling mechanism gives us a backward propagation model. This
backward propagation lets us manage all the exceptional flows in one location there by
making the program easy to understand.
Mostly we use runtime exception as a super class for all our customized exceptions because
these are the exceptions that occur during the runtime of a program. Therefore, it is safe to
say that all our customized exceptions fall in the category unchecked exceptions.
Second important topic that you will study in this lab is the file handling mechanism of Java.
Unlike C++, Java has a very rich library for file handling. Basically Java divides the filing into
two different streams. One is a character stream and the other is byte stream. These both
streams have almost the same functionalities and the major difference is that the character
stream reads and write 16 bit character and on the other hand the byte stream as it is clear
from its name can only read write one byte at a time.
We can also say that in both the streams there are two streams sections. One section deals
with the data sink stream which deals with only read and write operations. The other
section provides the utility classes for reading and writing. For example, BufferedReader is
a class that provides extra capability to character streams to read a line of data instead of
just a single character. Similar type of classes also exists for byte streams.
It is important to note that the all these streams are in java.io package. All the classes in
java.io package generate a checked IO exception. Therefore, you must handle these
exceptions or you won’t be able to run the program. Alternately you can use the following
line with the function definition in which you are using IO package to ignore the IO
exception generated by the code.
3. Concept Map
The new operator used in the above example creates an object of customized exception
class which is then thrown. This is the object which is ready for backward propagation.
throws keyword as discussed earlier is used in scenarios where you want to forward the
exception to the JVM or some intermediate calling method. The throws keyword is written
at the end of the function signature that does not want to handle such exception. If no
method handles the exception then the exception is finally caught by JVM, which displays
the data held by the object and terminates the program. Following code example will
forward all the exceptions to JVM that occur in main().
Page 39
First option has been discussed and implemented in 2nd Lab. Today we will discuss the
input mechanism using BufferedReader class. Following example shows you how to take
input
inp.readline() reads a line from a console and returns a string which can be used in a
program. BufferedReader was used to take input since JDK version 1.4. After JDK version
1.5 a new scanner class was introduced which has data type specific methods to take input.
Following code shows how to take input using Scanner class.
In this section, you will study how to make and run a customized exception.
4.1. Tools
javac MyClass.java
Page 40
Refer to Lab 1 sec 6.2 for details.
If the above command executed successfully then you will see output of the program.
This task is designed to guide you towards creating your own exception and running the
program.
Creating your own exception is basically a very easy task. There are only a handful of
sequence of steps that you can follow each time to create your own exception.
1. Open Notepad and type in the following code. Save the file by the name of
MyException.java
publicclassMyException extendsRuntimeException
{
publicMyException(String s)
{
super(s);
}
}
MyException is the name of the customized exception class. The only difference
between this class and other classes is that it is extended by the RuntimeException.
That is the only thing that you have to do to make a customized exception. The super()
function initializes the resource of the super class with your custom message.
2. Open the Notepad again and enter the following code to test the customized exception.
publicclass MyExceptionDemo
{
publicstaticvoidmain(String [] args) throwsException
{
for(inti=0;i< 5;i++)
{
System.out.println(""+i);
Page 41
if( i == 3)
{
thrownewMyException("Exception: The value of i is equal to 3");
}
}
}
}
3. Compile the above classes and run the program with the following statement.
java MyExceptionDemo
When the value of i becomes equal to 3 it will execute a block of code which throws the
exception. Since there is no handler written therefore, the control will be transferred to
the JVM. JVM will display the exception data. You will see the following line at the end of
your output and after that your program will terminate.
1. Create a file named input.txt in the current working directory. Save and close the file
after adding the following line in that text file.
import java.io.*;
3. Save the file by the name of FileReaderDemo. Compile and execute the program. You
Page 42
will see the following line on the screen after the successful execution of the program.
SANA ALI
5. Practice Task
This section will provide more practice exercises related to development. You need to finish the
tasks in the required time. When you finish them, submit these tasks into the
https://moellim.riphah.edu.pk/.
Write a program that reads two numbers from the file and save values in the respective variable. The input file is
displayed in the figure. After storing display the value.
HINT: “split ()” method will be used to separate the strings
You have to take a number as input from the user using a Buffered Reader which will define
a maximum number of games played by a user. A file contains number of games played by
the user. If they are less than the allowed maximum number, it is ok. But if any user have
played more than defined limit, display a message to charge him for the remaining.
Sample file can be:
After completing this lab, student will be able to understand java streams and customized
exceptions.
Page 43
5.5. Testing
This section provides you the test cases to test the working of your program. If you get the
desired mentioned outputs for the given set of inputs then your program is right.
6. Further Reading
6.1. Books
Text Book:
Java: How to Program by Paul J. Deitel, Harvey M. Deitel. Eighth Edition
Java Beginners Guide: http://www.oracle.com/events/global/en/java-
outreach/resources/java-a-beginners-guide-1720064.pdf
6.2. Slides
The slides and reading material can be accessed from the folder of the class instructor
available at https://moellim.riphah.edu.pk/
Page 44
MODES WHAT IT IMPLIES
r Read-only mode.
The file pointer is placed at the beginning of the file.
This is the default mode.
r+ Read-write mode. The file pointer will be at the beginning of the file.
w Write-only mode.
Overwrites the file if the file exists.
If the file does not exist, creates a new file for writing.
w+ Read-write mode.
Overwrites the existing file if the file exists.
If the file does not exist, creates a new file for reading and writing.
a Write-only mode.
The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode.
If the file does not exist, it creates a new file for writing.
r Read-only mode.
The file pointer is placed at the beginning of the file.
This is the default mode.
r+ Read-write mode. The file pointer will be at the beginning of the file.
w Write-only mode.
Overwrites the file if the file exists.
If the file does not exist, creates a new file for writing.
w+ Read-write mode.
Overwrites the existing file if the file exists.
If the file does not exist, creates a new file for reading and writing.
a Write-only mode.
The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode.
If the file does not exist, it creates a new file for writing.
Page 45