Lab Manual-Exception Handling

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

LAB

MANUAL
Course: CSC241-Object Oriented Programming

Department of Computer Science

Learning Procedure
1) Stage J (Journey inside-out the concept)
2) Stage a1 (Apply the learned)
3) Stage v (Verify the accuracy)
4) Stage a2 (Assess your work)

CCS241 –Lab Manual 1


COMSATS Institute of Information Technology (CIIT)
Islamabad
LAB # 13

Statement Purpose:
1. Understanding exception-throwing methods.
2. Using try-catch to handle exceptions.
3. Understanding and writing custom exceptions.

Activity Outcomes:
This lab teaches you the following topics:

 Exception handling
 (try, catch, finally, throw and throws) to handle exceptions.
Instructor Note:
As pre-lab activity, read Chapter 9 from the book, (Absolute Java, Savitch, W. & Mock, K., 5th
Edition (2012), Pearson.), and also as given by your theory instructor.

CCS241 –Lab Manual 81


1) Stage J (Journey)
Introduction
A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code. When an exceptional condition arises, an object representing that
exception is created and thrown in the method that caused the error. That method may choose
to handle the exception itself, or pass it on. Either way, at some point, the exception is caught
and processed. Exceptions can be generated by the Java run-time system, or they can be
manually generated by your code. Exceptions thrown by Java relate to fundamental errors
that violate the rules of the Java language or the constraints of the Java execution
environment. Manually generated exceptions are typically used to report some error condition
to the caller of a method. Java exception handling is managed via five keywords: try, catch,
throw, throws, and finally.

Exception-Throwing Methods

Runtime errors appear in Java as exceptions, exception is a special type of classes that could
be thrown to indicate a runtime error and provide additional data about that error. If a method
is declared to throw an exception, any other method calls it should deal with this exception by
throwing it (if it appears) or handle it. Recalling reading from user using BufferedReader
class, we used to declare main method from which we call readLine() using throws
IOException, this because readLine() is declared to throw that exception.

import java.io.*;
class ReadFromUser{
public static void main(String[] args) throws IOException{
.
.
.
}
}
If we wish to write a method that simplifies reading from user, you may want to declare it to
throw IOException.

import java.io.*;
class ReadFromUser{
public static void main(String[] args) throws IOException{
String in = read("Enter your name: ");
}
public static String read(String message) throws IOException{
System.out.print(message);
BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
String input = in.readLine();
return input;
}
}

CCS241 –Lab Manual 82


In the previous code, if an exception occurs in readLine() method, this exception is thrown as
it is to read method, which originally called it, because this last one is also declared to throw
that exception, it also throws it as it is to main method, which originally called it, finally, the
exception is throws to JVM which prints it out on the screen so the user can know there was
error.

try-catch Exception Handling


Another technique for handling runtime errors is to use try-catch block to handle different
types of exceptions and take appropriate action instead of throwing them to the user. The
format of try-catch block is the following.
try{
//Statement(s) that may throw exceptions
}catch(Exception e){
//Statement(s) to handle exception.
}
For example, we can place readLine() method which throws IOException in a try-catch block
as the following.

BufferedReader in = new BufferedReader new InputStreamReader(System.in));


String input;
try{
input = in.readLine();
}catch(IOException e){
System.out.println("Error occurred");
}

When we are expecting more than one exception, we can use several catch blocks, each one
for different type of exceptions. For example, when reading a string using BufferedReader
and converting it to integer, you can expect two different exceptions: IOException and
NumberFormatException which occurs when the provided string cannot be converted to
integer.

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));


String input;
try{
input = in.readLine();
int x = Integer.parseInt(input);
}catch(IOException e){
System.out.println("Error reading input");
}catch(NumberFormatException err){
System.out.println("This is not a valid number");
}

Finally
You can attach a finally-clause to a try-catch block. The code inside the finally clause will
always be executed, even if an exception is thrown from within the try or catch block. If your
code has a return statement inside the try or catch block, the code inside the finally-block will
get executed before returning from the method. Here is how a finally clause looks:

public void openFile(){


CCS241 –Lab Manual 83
FileReader reader = null;

CCS241 –Lab Manual 84


try {
reader = new FileReader("someFile");
int i=0;
while(i != -1){
i = reader.read();
System.out.println((char) i );
}
} catch (IOException e) {
//do something clever with the exception
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
//do something clever with the exception
}
}
System.out.println("--- File End ---");
}
}

No matter whether an exception is thrown or not inside the try or catch block the code inside
the finally-block is executed. The example above shows how the file reader is always closed,
regardless of the program flow inside the try or catch block.

Note: If an exception is thrown inside a finally block, and it is not caught, then that finally
block is interrupted just like the try-block and catch-block is. That is why the previous
example had the reader.close() method call in the finally block wrapped in a try-catch block:

finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
//do something clever with the exception
}
}
System.out.println("--- File End ---");
}

2) Stage a1 (apply)
Lab Activities:
Activity 1:
The example below shows the procedure for catching IndexOutOfBounds and InputMismatch
exception.
.

CCS241 –Lab Manual 85


CCS241 –Lab Manual 86
Solution:
importjava.util.InputMismatchException;
importjava.util.Scanner;
public class Marks {
public static void main(String args[]){
Scanner s=new Scanner(System.in);
try{
int[] marks = new int[5];
for(inti=0;i<=5;i++){
System.out.println("Enter marks for "+i+"st subjects :");
marks[i]=s.nextInt();
}
}

catch(InputMismatchException h){
System.out.println("Please enter correct number!");
}
catch(ArrayIndexOutOfBoundsExcepti
on e){ System.out.println("The error
is"+e);

}
catch(Exception ex)
{
System.out.println("The error is"+ex);
}
}
}

Activity 2:
The example below shows the procedure for using throw keyword.

Solution:
public class Exceptionclass
{
public static void main(String args[]){
try{

throw new Exception();


}
catch(Exception e){
System.out.println("Error!!!");
}

Activity 3:
CCS241 –Lab Manual 87
In some cases while developing our own applications, we need to specify custom types of
exceptions to handle custom errors that may occur during program execution. A custom
exception is a class that inherits Exception class or any of its subclasses, since inheritance is

CCS241 –Lab Manual 88


beyond the scope of this course, we will define it as using extends Exception in class
declaration.

Solution:
class MyCustomException extends Exception{

private String message;


public MyCustomException(String message){
this.message = message;
}
public String toString(){
return message;
}
}
To use your custom exception, declare an object of it and throw that object using throw
keyword. It is optional to declare the method containing throw statement with throws
keyword. In the following example, the program reads student id, this id should be of length
7 and consists only of digits, otherwise it throws an exception.
class InvalidIDException extends Exception{

private String message;


public InvalidIDException(String message){
this.message = message;
}
public String toString(){
return message;
}
}

Import javax.swing.*;
class StudentsData{
public static void main(String[] args){
String id, name;
name = JOptionPane.showInputDialog("Enter student name");
id = JOptionPane.showInputDialog("Enter student ID");

try{
verfyID(id);
}
catch(InvalidIDException e){
JoptionPane.showMessageDialog(null, e.toString());
}
}
public static void verifyID(String id) throws InvalidIDException
{
if(id.length() != 7){
throw new InvalidIDException("Check ID length");
}
try{
CCS241 –Lab Manual 89
Long.parseLong(id);
}
catch(Exception err){
throw
new InvalidIDException("ID can contain only digits");
}
}
}

CCS241 –Lab Manual 90

You might also like