Lab 5 - Exception Handling
Lab 5 - Exception Handling
Lab-05
Exception Handling
Lab 5: Exception Handling
Table of Contents
1. Introduction 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
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
9. Evaluation criteria 54
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.
4. Concept Map
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.
Generating exception and handing over to the runtime environment is known to throw an
exception
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.
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);
}
catch (NullPointerException Ex2) {
System.out.println("2: " + Ex2);
}
Output:
0:b =1
2: java.lang.NullPointerException
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.
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);
}
try {
statements //that would possibly cause exceptions
}
catch (exception e)
{
statements //Exception handling code
}
. . . //multiple catch segments
You must solve the following problems at home before the lab.
After reading the reference material mentioned in the introduction, now you are ready to perform
homework assigned to you
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.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?
6. Procedure& Tools
In this section, you will study how to work with exception handling and creating packages using
JDK.
6.1 Tools
This task is designed to guide you towards creating your own abstract class and interface and
running the program.
This example shows you how exception may occur in a program and how to handle it
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]);
}
}}
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.
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
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).
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.
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
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.
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).
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$\