Lab 3 Exception Handling

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Lab Manual for Advance Computer Programming

Lab-03
Exception Handling
Lab 3: Exception Handling and Packages

Table of Contents
1. Introduction 27

2. Objective of the experiment 27

3. Concept Map 27
3.1. Error 27
3.2. Exception 28
3.2.1. Throwing Exception: 28
3.3. Hierarchy of Exceptions 28
3.3.1. Runtime Exceptions(unchecked) 29
3.3.2. IO Exceptions (checked) 30
3.4. Try, catch and finally 30

4. Procedure& Tools 31
4.1. Tools 31
4.2. Setting-up JDK 1.7 31
4.2.1. Compile and run a Program 31
4.3. Walkthrough Task 31
4.3.1. Implementing Exception Class 31

5. Practice Tasks 32
5.1. Practice Task 1 32
5.2. Practice Task 2 33
5.3. Practice Task 3 33
5.4. Practice Task 4 33
5.5. Out comes 33
5.6. Testing 33

6. Further Reading 34
6.1. Books 34
6.2. Slides 34

Page 26
Lab 3: Exception Handling and Packages

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

3. Concept Map

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

3.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:

Page 27
Lab 3: Exception Handling and Packages

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

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

3.2.1. Throwing Exception:

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

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

Page 28
Lab 3: Exception Handling and Packages

Figure 1: Hierarchy of Exceptions

3.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);

Page 29
Lab 3: Exception Handling and Packages

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

Output:

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

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

3.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);
}

Page 30
Lab 3: Exception Handling and Packages

Following example shows the use of finally block.

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.

4. Procedure& Tools

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

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 and run a Program

Refer to lab 1 sec 7.2

4.3. Walkthrough Task

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

4.3.1. Implementing Exception Class

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

Page 31
Lab 3: Exception Handling and Packages

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]);
}
}}

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.

5. Practice Tasks

This section will provide more practice exercises related to development. You need to finish the
tasks in the required time. When you finish them, put these tasks into the
https://moellim.riphah.edu.pk/.

5.1. Practice Task 1

Generate the scenarios for following exceptions:


 ArithmeticException
 ArrayIndexOutOfBoundsException
 NullPointerException
 NumberFormatException

Page 32
Lab 3: Exception Handling and Packages

5.2. Practice Task 2

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

5.3. Practice Task 3

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 water, then also throw
an exception.

5.4. Practice Task 4

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

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

5.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”)

Page 33
Lab 3: Exception Handling and Packages

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

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/

Page 34

You might also like