Lab Manual-Exception Handling
Lab Manual-Exception Handling
Lab Manual-Exception Handling
MANUAL
Course: CSC241-Object Oriented Programming
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)
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.
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;
}
}
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.
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:
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.
.
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{
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
Solution:
class MyCustomException extends Exception{
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");
}
}
}