0% found this document useful (0 votes)
75 views11 pages

Lab 5 - Exception Handling

This lab manual covers exception handling in Java. It introduces key concepts like errors vs exceptions, throwing exceptions, and the hierarchy of exceptions. Runtime and IO exceptions are specifically discussed. The manual provides an activity timebox, objectives, and concept overview. It describes setting up the JDK, walking through example tasks, practice tasks to be completed, and an evaluation with multiple unseen tasks to be finished within an hour.

Uploaded by

Misbah Ullah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views11 pages

Lab 5 - Exception Handling

This lab manual covers exception handling in Java. It introduces key concepts like errors vs exceptions, throwing exceptions, and the hierarchy of exceptions. Runtime and IO exceptions are specifically discussed. The manual provides an activity timebox, objectives, and concept overview. It describes setting up the JDK, walking through example tasks, practice tasks to be completed, and an evaluation with multiple unseen tasks to be finished within an hour.

Uploaded by

Misbah Ullah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Lab Manual for Advance Computer Programming

Lab-05
Exception Handling
Lab 5: Exception Handling

Table of Contents
1. Introduction 46

2. Activity Time boxing 46

3. Objective of the experiment 46

4. Concept Map 46
4.1 Error 47
4.2 Exception 47
4.2.1 Throwing Exception: 47
4.3 Hierarchy of Exceptions 47
4.3.1 Runtime Exceptions(unchecked) 48
4.3.2 IO Exceptions (checked) 49
4.4 Try, catch and finally 49

5. Homework before Lab 50


5.1 Problem Solution Modeling 50
5.2 Practices from home 50
5.2.1 Task-1 50
5.2.2 Task-2 50

6. Procedure& Tools 51
6.1 Tools 51
6.2 Setting-up JDK 1.7 [Expected time = 5mins] 51
6.2.1 Compile and run a Program 51
6.3 Walkthrough Task [Expected time = 30mins] 51
6.3.1 Implementing Exception Class 51

7. Practice Tasks 52
7.1 Practice Task 1 [Expected time = 15mins] 52
7.2 Practice Task 2 [Expected time = 15mins] 52
7.3 Practice Task 3 [Expected time = 15mins] 52
7.4 Practice Task 4 [Expected time = 15mins] 53
7.5 Out comes 53
7.6 Testing 53

8. Evaluation Task (Unseen) [Expected time = 60mins for two tasks] 54

9. Evaluation criteria 54

10. Further Reading 54


10.1 Books 54
10.2 Slides 54

Department of Computer Science, Page 45


C.U.S.T.
Lab 5: Exception Handling

Lab 3: Exception Handling

1. Introduction

You have learnt Java constructs, abstract classes and interfaces. In this lab, you will test the
theory by generating and handling exceptions in your code.

The responsibility of the programmer is not just producing the code but to produce the work with
quality, such that its performance is robust and does not fail in unexpected ways in exceptional
scenarios. Java is a robust language therefore it provides ways to make your program adapt with
the changing needs and requirement. Sometimes due to design problems or changed scenarios,
our programs may crash or behave abnormal in certain conditions so we need to handle all these
conditions in our programs. Such conditions are known as exceptions. For example, divide by
zero is the most common problem for which it has already been established that its result is
infinity. Our systems cannot handle this scenario so the program terminates. In this lab, we will
study the ways to handle such unexpected scenarios.

Relevant Lecture Material

a) Revise Lecture No. 5 and 6


b) Text Book: Java: How to Program by Paul J. Deitel, Harvey M. Deitel
1. Read pages: 813-831
2. Revise the code reusability concepts provided by C++

2. Activity Time boxing

Table 1: Activity Time Boxing


Task No. Activity Name Activity time Total Time
5.1 Evaluation of Design 20mins 20mins
6.2 Setting-upPath for JDK 5mins 5mins
6.3 Walkthrough Tasks 30mins 30mins
7 Practice tasks 15mins for each task 60mins
8 Evaluation Task 60mins for all assigned task 55mins

3. Objective of the experiment

 To get basic understanding of Object Oriented concept of reusability.


 To write programs which can adapt with the changing environment/ requirements.
 To get an understanding of identifying basic exceptions and fix them.

4. Concept Map

Department of Computer Science, Page 46


C.U.S.T.
Lab 5: Exception Handling

This section provides you the overview of the concepts that will be discussed and implemented
in this lab.

4.1 Error

Exception conditions that do not link directly to the program or the application may not be
responsible for that. The application or program cannot handle or foresee that particular
situation. For example situations like:

1. Hardware malfunction
2. System got stuck.
3. Electricity supply is cutoff to the system and application stops.

4.2 Exception

If some alternate flow occurs within some method, it creates the object called exception objects
and hands off to the Java runtime environment. Exception object has information regarding the
type of exception and state of the program; when that exceptional conditional arose.

4.2.1 Throwing Exception:

Generating exception and handing over to the runtime environment is known to throw an
exception

4.3 Hierarchy of Exceptions

Java is object oriented therefor, it has placed all the exception classes in a proper hierarchy.
Figure 1 shows the hierarchy of the Java exception. The top level classes are generic classes and
bottom level classes are the specialized classes. The dynamic binding behavior applies on this
hierarchy meaning that the reference of top level class can handle or hold the object of
specialized classes.

Department of Computer Science, Page 47


C.U.S.T.
Lab 5: Exception Handling

Figure 1: Hierarchy of Exceptions

4.3.1 Runtime Exceptions(unchecked)

Exceptional conditions that are unpredictable and undetectable at runtime fall in the category of
runtime exceptions.  Runtime exceptions are specified by RuntimeException class and its
subclasses. Following example show the scenario of a run time exception named
NullPointerException.

int array1[]=null;
int b=1;
System.out.println("0: b = " + b);
try {
array1[b] = 100 / b;
System.out.println( "0: array1[" + b + "] = " + array1[b]);
}
catch (ArithmeticException Ex1) {
System.out.println( "1: " + Ex1);

Department of Computer Science, Page 48


C.U.S.T.
Lab 5: Exception Handling

}
catch (NullPointerException Ex2) {
System.out.println("2: " + Ex2);
}

Output:

0:b =1
2: java.lang.NullPointerException

4.3.2 IO Exceptions (checked)

Checked exceptions are those exceptions that are expected and needs to be fixed before the
compiler generates bytecode. The compiler won’t generate the bytecode if the checked exception
is not handled properly.

For example, user wants to read data from a file. The program prompts the user for file name and
he provides the name of the file that does not exists. java.io.FileNotFoundException is thrown.
This scenario is known before runtime that user may provide nonexistent file. A well written and
robust program will provide the catch block for handling this exception and notify the user when
it is encountered. Java asks you to provide a try catch block to handle such exceptions. Since
Java enforces this rule at compile time therefore, we say that all exceptions of that sort are
checked exceptions.

4.4 Try, catch and finally

Code block where exception may occur is enclosed within try block andthat can be checked or
unchecked exceptional flow blocks. Following example shows the try block.

try {
int a = 100 / 0;
System.out.println (a);
}

First the code inside the try block is executed. If exception occurs then the object of
corresponding exception is thrown. In the above example object of ArithmeticException class is
thrown. Now if this thrown object matches with any of the catch blocks then catch block is
executed otherwise the programresumes its execution to the next statement.
.
catch (ArithmeticException Ex1) {
System.out.println( "1: " + Ex1);
}

Following example shows the use of finally block.

Department of Computer Science, Page 49


C.U.S.T.
Lab 5: Exception Handling

try {
statements //that would possibly cause exceptions
}
catch (exception e)
{
statements //Exception handling code
}
. . . //multiple catch segments

finally { // always executed(optional)


statements
}

Finally clause is always executed whether exception occurs or not.

5. Homework before Lab

You must solve the following problems at home before the lab.

5.1 Problem Solution Modeling

After reading the reference material mentioned in the introduction, now you are ready to perform
homework assigned to you

5.1.1 Problem description:

What are the differences in compile time and runtime exceptions? Give at least five examples of
each type. Also identify the scenarios where exception handling is useful in implementing large
system.

5.2 Practices from home

5.2.1 Task-1

Write a program to show the scenario where the programmer catches the generalized exception
first and specialized exception later.

5.2.2 Task-2

What are checked and unchecked exceptions? What could be possible benefits or drawbacks of
handling exceptions in your program?

Department of Computer Science, Page 50


C.U.S.T.
Lab 5: Exception Handling

6. Procedure& Tools

In this section, you will study how to work with exception handling and creating packages using
JDK.

6.1 Tools

Java Development Kit (JDK) 1.7

6.2 Setting-up JDK 1.7 [Expected time = 5mins]

Refer to Lab 1 sec 6.2.

6.2.1 Compile and run a Program

Refer to lab 1 sec 7.2

6.3 Walkthrough Task [Expected time = 30mins]

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

6.3.1 Implementing Exception Class

This example shows you how exception may occur in a program and how to handle it

Follow the following steps to create a class.

1. Open Notepad and type the following code.

import java.io.*;
public class TryException
{
public static void main(String arg[])
{
try {
int A1[]=new int [4];
System.out.println("Element four in array A1: "+ A1[4]);
}
catch (ArrayIndexOutOfBoundsException E){
System.out.println("Exception thrown " + E]);
}
}}

Department of Computer Science, Page 51


C.U.S.T.
Lab 5: Exception Handling

2. Save the file as TryException.java.

3. Compile the class and run the programfor testing.

4. It will generate following exception:ArrayIndexOutOfBoundsException.

5. Look at the statement A1[4]. Size of array is 4 that means index 0 to 3 but, we are trying to
access 4th index which is inaccessible for array A1 that's why exceptions occurred and
program cannot run smoothly. The control will shift to the catch block and no exception type
is displayed.

6. To correct this, access indexes only in the range 0 to 3.

7. Practice Tasks

This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the
following folder:
\\dataserver\assignments$\Advanced Computer Programming\Lab3

7.1 Practice Task 1 [Expected time = 15mins]

Generate the scenarios for following exceptions:


a. ArithmeticException
b. IndexOutOfBoundsException
c. NullPointerException
d. NumberFormatException

7.2 Practice Task 2 [Expected time = 15mins]

Create an Animal class which have three methods (eat, sleep, walk). Extend a class
Reptile that overrides walk method. Extend class Snake from Reptile that overrides the
walk method. If a walk method is called form snake class, generate an exception (as
snakes can’t walk).

7.3 Practice Task 3 [Expected time = 15mins]

Create a program in which you have two Rides (Car, Boat) and two locations (Land, Water).
Ask from the user about the ride and the location.
If user selects ride a car and location water, then throw an exception.
Similarly, if user selects ride a boat and location land, then also throw an exception.

Department of Computer Science, Page 52


C.U.S.T.
Lab 5: Exception Handling

7.4 Practice Task 4 [Expected time = 15mins]

There are N number of bottles and M number of glasses that will be filled from these bottles.
Each bottle can fill up 5 glasses. You are to write a program that will ask user to input N and M,
and check if the bottles are enough to fill M glasses. If bottles are not enough throw an exception
informing the user. HINT: Total number of glasses that can be made from bottles =
5*number of bottles

7.5 Out comes

After completing this lab, student will be able to understand the purpose of packages. They will
be able to use existing Java packages. They will also understand the exception handling.

7.6 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 Input Sample Output


java.lang.ArithmeticException at
ExceptionExample.main(ExceptionExample.java:”line
number”)
java.lang.IndexOutOfBoundsException: Index
messageat
ExceptionExample.main(ExceptionExample.java:”line
number”)
java.lang.NullPointerException: Null Pointer Message
at
ExceptionExample.main(ExceptionExample.java:”line
number”)

Test Cases for Practice Task-3

Sample Input Sample Output


Car, Road Welcome to the ride!
Car, Water Mismatch Exception Handled
Program Ended

Test Cases for Practice Task-4

Sample Input Sample Output


3
20 LessNumberOfBottlesException

Department of Computer Science, Page 53


C.U.S.T.
Lab 5: Exception Handling

8. Evaluation Task (Unseen) [Expected time = 60mins for two tasks]

The lab instructor will give you unseen task depending upon the progress of the class.

9. Evaluation criteria

The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).

Table 3: Evaluation of the Lab


Sr. No. Task No Description Marks
1 4 Problem Modeling 20
2 6 Procedures and Tools 10
3 7 Practice tasks and Testing 35
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

10. Further Reading


This section provides the references to further polish your skills.

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

10.2 Slides

The slides and reading material can be accessed from the folder of the class instructor available
at \\dataserver\jinnah$\

Department of Computer Science, Page 54


C.U.S.T.

You might also like