0% found this document useful (0 votes)
32 views

Lab 4 Exception Handling and Java Filing

This lab manual discusses exception handling and file handling in Java. It introduces creating custom exceptions by extending the RuntimeException class and implementing a simple file reader. The document provides an overview of exception handling concepts like throw and throws clauses. It describes how to compile and run Java programs. It includes a walkthrough task to guide students in creating a custom MyException class and testing it. It also outlines steps to implement a basic file reader. The lab aims to help students understand custom exceptions, Java I/O streams, and reading/writing files.

Uploaded by

DeadPool Pool
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Lab 4 Exception Handling and Java Filing

This lab manual discusses exception handling and file handling in Java. It introduces creating custom exceptions by extending the RuntimeException class and implementing a simple file reader. The document provides an overview of exception handling concepts like throw and throws clauses. It describes how to compile and run Java programs. It includes a walkthrough task to guide students in creating a custom MyException class and testing it. It also outlines steps to implement a basic file reader. The lab aims to help students understand custom exceptions, Java I/O streams, and reading/writing files.

Uploaded by

DeadPool Pool
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Lab Manual for Advance Computer Programming

Lab-04
Exception Handling and Java Filing
Table of Contents
1. Introduction 38

2. Objective of the experiment 39

3. Concept Map 39
3.1. Throw Clause 39
3.2. Throws Clause 39
3.3. king input in Java 39

4. Procedure & Tools 40


4.1. Tools 40
4.2. Setting-up JDK 1.7 40
4.2.1. Compile a Program 40
4.2.2. Run a Program 41
4.3. Walkthrough Task[Expected time = 30mins] 41
4.3.1. Implementing your own exception class 41
4.3.2. Implementing a simple file reader 42

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.

public static void main(String args[ ]) throws IOException {


}
Page 38
2. Objective of the experiment

 To get basic understanding of customized exception.


 To understand the scenarios in which to use customized exceptions.
 To get familiar with the basic IO streams available in Java.
 To be able to read and write data in a file.

3. Concept Map

3.1. Throw Clause

Throw keyword is provided by Java to throw an object of a customized exception. For


example, if we want to throw, balance less than 5000 then we will use a throw key like the
following.

throw new CustomException(“Warning: Balance less than 5000”);

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.

3.2. Throws Clause

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().

public static void main(String args[ ]) throws Exception {


}

3.3. king input in Java

There are three ways of taking input from console

1. Command line arguments


2. Using Buffered Reader
3. Using Scanner

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

public class Input{


public static void main (String[] args) throws IOException
{
BufferedReader inp = new BufferedReader (new InputStreamReader(System.in));
String in= inp.readline();
}
}

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.

public class ScannerInput{


public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int num;
System.out.print("Enter a number: ");
num = sc.nextInt();
}
}

4. Procedure & Tools

In this section, you will study how to make and run a customized exception.

4.1. Tools

Java Development Kit (JDK) 1.7

4.2. Setting-up JDK 1.7

Refer to Lab 1 sec 6.2.

4.2.1. Compile a Program

Use the following command to compile the program.

javac MyClass.java

Page 40
Refer to Lab 1 sec 6.2 for details.

4.2.2. Run a Program

Use the following command to run the program.


java MyClass

If the above command executed successfully then you will see output of the program.

4.3. Walkthrough Task[Expected time = 30mins]

This task is designed to guide you towards creating your own exception and running the
program.

4.3.1. Implementing your own exception class

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.

Exception: The value of i is equal to 3

4.3.2. Implementing a simple file reader

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.

“This is Lab 4 of Advance Computer Programming”

2. Open Notepad and type the following code.

import java.io.*;

public class FileReaderDemo{

public static void main(String args[])throws IOException{

File in = new File("input.txt");


FileReader fr = new FileReader(in);
int c=0;
while((c=fr.read()) != -1)
System.out.print(c);
fr.close();
}
}

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.

“This is Lab 4 of Advance Computer Programming”

Sample Text File

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/.

5.1. Practice Task 1

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

Sample input Sample Output

5.2. Practice Task 2


Write a program to reads data from the file. Your program should count number of capital
letters, small letters and digits read from the file. Display and Save the count in another file.

5.3. Practice Task 3

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:

User Games Played


Sadia 5
Ali 7

5.4. Out comes

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.

Test Cases for Practice Task-1

Sample File Sample Output


SanaAli Sana
Ali

Test Cases for Practice Task-2

Sample File Sample Output and file 2


Program 2 to reads data from the file 1 Capital letter
2 Samll Letters
1 digit

Test Cases for Practice Task-3

Sample Input Sample Output


Maximum Limit-6 Sana can play 1 more.
Ali is charged for one game.

6. Further Reading

This section provides the references to further polish your skills.

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/

6.3. File Modes in Java

The Different Modes of Opening a File

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.

a+ Read and write mode.


The file pointer is at the end of the file if the file exists.
The file opens in the append mode.
If the file does not exist, it creates a new file for reading and writing.

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.

a+ Read and write mode.


The file pointer is at the end of the file if the file exists.
The file opens in the append mode.
If the file does not exist, it creates a new file for reading and writing.

Page 45

You might also like