Unit 4
Unit 4
4.0 INTRODUCTION
During programming in languages like c, c++ you might have observed that even
after successful compilation some errors are detected at runtime. For handling these
kinds of errors there is no support from programming languages like c, c++. Some
error handling mechanisms like returning special values and setting flags are used to
determine that there is some problem at runtime.
In C++ programming language there is a very basic provision for exception handling.
Basically exception handlings provide a safe escape route from problem or clean-up
of error handling code.
In Java exception handling is the only semantic way to report error .In Java exception
is an object, which describes error condition, occurs in a section of code. In this unit
we will discuss how exceptions are handled in Java, you will also learn to create your
own exception classes in this unit.
4.1 OBJECTIVES
4.2 EXCEPTION
61
Object Oriented Concepts
and Exceptions Handling
If you attempt in a Java program to carry out an illegal operation, it does not
necessarily halt processing at that point. In most cases, the JVM sees for the
possibility of catching the problem and recovering from it.
If the problems are such which can be caught and recovery can be provided, then we
say the problems are not fatal, and for this the term exception is used rather than
error.
Causes of Exception
Exception arises at runtime due to some abnormal condition in program for example
when a method. For division encounters an abnormal condition that it can't handle
itself, i.e. “divide by zero,” then this method may throw an exception.
Exception If a program written in Java does not follow the rule of Java language or violates the
is an Java execution environment, constraints exception may occur. There may be a
abnormal manually generated exception to pass on some error reports to some calling certain
condition methods.
Now let us see how to write programs in Java, which take care of exceptions
handling.
See the program given below:
//program
public class Excep_Test
62
Exceptions Handling
{
public static void main(String[] args)
{
int data[] = {2,3,4,5};
System.out.println("Value at : " + data[4]);
}
}
Output:
java.lang.ArrayIndexOutOfBoundsException
at Excep_Test.main(Excep_Test.java:6)
Exception in thread "main"
To catch an exception in Java, you write a try block with one or more catch clauses.
Each catch clause specifies one exception type that it is prepared to handle. The try
block places a fence around the code that is under the watchful eye of the associated
catchers. If the bit of code delimited by the try block throws an exception, the
associated catch clauses will be examined by the Java virtual machine. If the virtual
machine finds a catch clause that is prepared to handle the thrown exception, the
program continues execution starting with the first statement of that catch clause, and
the catch block is used for executing code to handle exception and graceful
termination of the program.
In this program you can observe that after the occurrence of the exception the
program is not terminated. Control is transferred to the catch block followed by try
block.
4.3.2 Catching Multiple Exceptions
Sometimes there may be a chance to have multiple exceptions in a program. You can
use multiple catch clauses to catch the different kinds of exceptions that code can
throw. If more than one exception is raised by a block of code, then to handle these
exceptions more than one catch clauses are used. When an exception is thrown,
different catch blocks associated with try block inspect in order and the first one
whose type (the exception type passed as argument in catch clause) matches with the
exception type is executed This code snippet will give you an idea how to catch
multiple exceptions.
//code snippet
63
Object Oriented Concepts
and Exceptions Handling
try
{
// some code
}
catch (NumberFormatException e)
{
//Code to handle NumberFormatException
}
catch (IOException e)
{
// Code to handle IOException
}
catch (Exception e)
{
// Code to handle exceptions than NumberFormatException and IOException
}
finally // optional
{
//Code in this block always executed even if no exceptions
}
//program
public class MultiCatch
{
public static void main(String[] args)
{
int repeat ;
try
{
repeat = Integer.parseInt(args[0]);
}
catch (ArrayIndexOutOfBoundsException e)
{
// pick a default value for repeat
repeat = 1;
}
catch (NumberFormatException e)
{
// print an error message
System.err.println("Usage: repeat as count" );
System.err.println("where repeat is the number of times to say Hello Java" );
System.err.println("and given as an integer like 2 or 5" );
return;
}
for (int i = 0; i < repeat; i++)
{
System.out.println("Hello");
}
}
}
Output:
Hello
64
Exceptions Handling
It is important to ensure that something happens upon exiting a block, no matter how
the block is exited. It is the programmer’s responsibility to ensure what should
happen. For this finally clause is used.
1) What is an exception? Write any three actions that can be taken after an
exception occurs in a program.
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
…………………………………………………………………………….
…………………………………………………………………………….
.
2) Is the following code block legal?
try
{
...
}
finally
{
...
}
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
…………………………………………………………………………….
…………………………………………………………………………….
3) Write a program to catch more than two exceptions.
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
…………………………………………………………………………….
4.3.3 Using finally clause
There are several ways of exiting from a block of code (the statements between two
matching curly braces). Once a JVM has begun to execute a block, it can exit that
block in any of several ways.
It could, for example simply exit after reaching the closing curly brace.
It could encounter a break, continue, or return statement that causes it to jump out of
the block from somewhere in the middle.
If an exception is thrown that isn’t caught inside the block, it could exit the block
while searching for a catch clause.
Let us take an example, of opening a file in a method. You open the file perform
needed operation on the file and most importantly you want to ensure that the file
65
Object Oriented Concepts
and Exceptions Handling
gets closed no matter how the method completes. In Java, this kind of desires are
fulfilled with the help of finally clause.
A finally clause is included in a program in the last after all the possible code to be
executed. Basically finally block should be the last block of execution in the program.
//program
public class Finally_Test
{
public static void main(String[] args)
{
try
{
System.out.println("Hello " + args[0]);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Hello, You are here after ArrayIndexOutOfBoundsException");
}
finally
{
System.out.println("Finally you have to reach here");
}
}
}
Output:
Hello, You are here after ArrayIndexOutOfBoundsException
Finally you have to reach here
Note: At least one clause, either catch or finally, must be associated with each try
block. In case you have both catch clauses and a finally clause with the same try
block, you must put the finally clause after all the catch clauses.
Unchecked exceptions
Basically, an unchecked exception is a type of exception for that you option that
handle it, or ignore it. If you elect to ignore the possibility of an unchecked
exception, then, as a result of that your program will terminate. If you elect to handle
an unchecked exception that occur then the result will depend on the code that you
have written to handle the exception. Exceptions instantiated from
RuntimeException and its subclasses are considered as unchecked exceptions.
Checked exceptions
66
Exceptions Handling
Checked exceptions are those that cannot be ignored when you write the code in your
methods. “According to Flanagan, the exception classes in this category represent
routine abnormal conditions that should be anticipated and caught to prevent program
termination.”
All exceptions instantiated from the Exception class, or from subclasses, of
Exception other than RuntimeException and its subclasses, must either be:
(i) Handled with a try block followed by a catch block, or
(ii) Declared in a throws clause of any method that can throw them
The conceptual difference between checked and unchecked exceptions is that
checked exceptions signal abnormal conditions that you have to deal with. When
you place an exception in a throws clause, it forces to invoke your method to deal
with the exception, either by catching it or by declaring it in their own throws clause.
If you don't deal with the exception in one of these two ways, your class will not
compile
67
Object Oriented Concepts
and Exceptions Handling
+ class java.lang.IllegalArgumentException
|
+ class java.lang.Error
Programming errors that should be detected in testing for example index out of
bounds, null pointer, illegal argument, etc. are known as runtime exception. Runtime
exceptions do need to be handled (They are of the types that can be handled), but
errors often cannot be handled.
The runtime exceptions are not necessarily to be caught. You don’t have to put a try-
catch for runtime exceptions, for example, every integer division operation to catch a
divide by zero or around every array variable to watch for whether it is going out of
bounds. But it is better if you handle possible runtime exceptions. If you think there is
a reasonable chance of such exceptions occurring.
68
Exceptions Handling
try
{
//operation code...
}
catch (Exception e)
{
//exception handling
}
catch (ArithmeticException ae)
{
// ArithmeticException handling
}
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
4) Differentiate between checked and unchecked exceptions.
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
If you don’t want explicitly catching handle an exception and want to declare that
your method throws the exception. This passes the responsibility to handle this
exception to the method that invokes your method. This is done with the throws
keyword.
69
Object Oriented Concepts
and Exceptions Handling
//code snippet
public static void copy (InputStream in, OutputStream out)
throws IOException
{
byte[] Mybuf = new byte[256];
while (true)
{
int bytesRead = in.read(Mybuf);
if (bytesRead == -1) break;
out.write(Mybuf, 0, bytesRead);
}
}
In this code snippet copy method throws IOException, and now the method invoke
copy method is responsible for handling IOException.
Sometime single method may have to throw more than one type of exception. In this
case the exception classes are just separated by commas. For example in the code:
public MyDecimal
public divide(MyDecimal value, int roundMode) throws ArithmeticException,
IllegalArgumentException
See the program given below written for showing how IllegalArgumentException
exceptions are thrown if arguments are not passed properly.
//program
class MyClock
{
int hours ,minutes, seconds;
public MyClock(int hours, int minutes, int seconds)
{
if (hours < 1 || hours > 12)
{
throw new IllegalArgumentException("Hours must be between 1 and 12");
}
if (minutes < 0 || minutes > 59)
{
throw new IllegalArgumentException("Minutes must be between 0 and 59");
}
if (seconds < 0 || seconds > 59)
{
throw new IllegalArgumentException("Seconds must be between 0 and 59");
}
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
public MyClock(int hours, int minutes)
{
this(hours, minutes, 0);
}
public MyClock(int hours)
{
this(hours, 0, 0);
}
70
Exceptions Handling
}
public class ThrowTest
{
public static void main( String args [])
{
try
{
MyClock clock = new MyClock(12, 67,80);
}
catch( IllegalArgumentException e)
{
System.out.println("IllegalArgumentException is caught....");
}
}
}
Output:
IllegalArgumentException is caught....
Most of the exception subclasses inherit all their functionality from the superclass
and they serve the purpose of exception handling. Sometimes you will need to create
your own exceptions types to handle specific situations that arises in your
applications. This you can do quite easily by just defining subclass of Exception
class. Exception class does not define any method of its own .Of course it inherits
methods of Throwable class. If you inherit Exception you have the method of
Throwable class available for your class. If needed you can override the methods of
Throwable class.
Now see the program given below to create exception subclass which throws
exception if argument passed to MyException class method compute has value
greater that 10.
//program
MyException extends Exception
{
private int Value;
MyException (int a)
{
Value = a;
}
public String toString()
{
return ("MYException [for Value="+ Value +"]");
}
}
class ExceptionSubClassDemo
{
static void compute(int a) throws MyException
{
System.out.println("Call compute method ("+a+")");
71
Object Oriented Concepts
and Exceptions Handling
if(a>10)
throw new MyException(a);
System.out.println("Normal Exit of compute method[for Value="+a +"]");
}
public static void main(String args[])
{
try
{
compute(5);
compute(25);
}
catch(MyException e)
{
System.out.println("MyException Caught :"+e);
}
}
}
Output:
Call compute method (5)
Normal Exit of compute method [for Value=5]
Call compute method (25)
MyException Caught: MYException [for Value=25]
You can say that when an exception is thrown by you ,it is like performing a kind of
structured go-to from the place in your program where an abnormal condition was
detected to a place where it can be handled. The Java virtual machine uses the class
of the exception object you throw to decide which catch clause, if any, should be
allowed to handle the exception.
But you cannot take an exception just as a transfer control from one part of your
program to another, it also transmits information. As mentioned earlier the exception
is a full-fledged object that you can define yourself. Also you can embed information
about the abnormal condition in the object before you throw it. The catch clause can
then get the information by querying the exception object directly.
The Exception class allows you to specify a String detail message that can be
retrieved by invoking getMessage() of Throwable class on the exception object. In
your program at the time of defining it you can give the option of specifying a detail
message like this:
class NotAcceptableValuException extends Exception
{
NotAcceptableValuException
{
}
NotAcceptableValuException (String msg)
{
super(msg);
}
}
new NotAcceptableValuException ()
new NotAcceptableValuException ("This Value is not Acceptable.")
Now a catch clause can query the object for a detail string, like this code snippet:
class MyValue
72
Exceptions Handling
{
public void serveCustomers()
{
try
{
// operations
}
catch (NotAcceptableValuException e)
{
System.out.println (“NotAcceptableValuException Caught:”+e);
}
}
}
will print:
NotAcceptableValuException Caught:" This Value is not Acceptable." provided
NotAcceptableValuException object is created as:
new NotAcceptableValuException ("This Value is not Acceptable.") ;
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
…………………………………………………………………………………
…
3) Dry run the following program and show the output:
//program
class MyStack
{
private int MaxSize;
private int size;
private Object[] ob1;
public MyStack(int cap)
{
ob1 = new Object[cap];
MaxSize = cap;
size = 0;
}
public void push(Object o) throws StackException
{
if (size == MaxSize)
73
Object Oriented Concepts
and Exceptions Handling
throw new StackException("overflow");
ob1[size++] = o;
}
public Object pop() throws StackException
{
if (size <= 0)
throw new StackException("underflow");
return ob1[--size];
}
public Object top() throws StackException
{
if (size <= 0)
throw new StackException("underflow");
return ob1[size-1];
}
public int size()
{
return this.size;
}
}
class StackException extends Exception
{
StackException() {}
StackException(String msg)
{
super(msg);
}
}
class StackTest
{
public static void main(String[] args)
{
MyStack s = new MyStack(5);
System.out.println("***** Welcome to Stack operations ****");
Test(s);
}
public static void Test(MyStack s)
{
try
{
s.push("Hi");
s.push("Java");
s.push(new Float(1.4));
s.push("Good for all");
s.push("Learn it");
s.push("Now"); // error!
}
catch(StackException se)
{
System.out.println(se);
}
try
{
System.out.println("Top of MyStack : " + s.top());
System.out.println("Popping data ...");
while (s.size() > 0)
System.out.println(s.pop());
}
catch(StackException se)
{
74
Exceptions Handling
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
4.7 SUMMARY
This unit discusses how Java goes to great lengths to help you deal with error
conditions. In this unit we have discussed how Java's exception mechanisms give a
structured way to perform a go-to from the place where an error occurs to the code
that knows how to handle the error. In this unit we have discussed different causes of
exception, using try, catch, finally, throw and throws clauses in exception handling.
This unit deals with ways to handle error conditions in a structured, methodical way.
This unit discusses types of exceptions, Throwable class hierarchy, and explains how
to write own exception subclasses.
4.8 SOLUTIONS/ANSWERS
2) Yes, it is legal. It is not necessary for a try statement to have a catch statement
if it has a finally statement. If the code in the try statement has multiple exit
points and no catch clauses are associated to the code, then code in the finally
statement is executed no matter how the try block is exited.
3)
//program
public class TwoCatch_Test
{
public static void main(String[] args)
{
try
{
int i = 1;
int data[] = {2,3,4,5};
System.out.println("Value at : " + data[2]);
i = i/(i-i);
}
catch( ArrayIndexOutOfBoundsException e)
{
System.out.println("Sorry you are trying to print beyond the size of data[]");
}
catch(ArithmeticException e)
{
System.out.println("Divide By 0 :"+e);
75
Object Oriented Concepts
and Exceptions Handling
}
}
}
Output:
Value at: 4
Divide By 0: java.lang.ArithmeticException: / by zero
Check Your Progress 2
1) This code will handle catch exceptions of type Exception; therefore, it will
catch any exception. This can be a poor implementation because you are losing
valuable information about the type of exception being thrown and making
your code less efficient. It is better to handle different exceptions on the basis
of their actual type, which may be ArithmeticException, or
IllegalArgumentException or anything else
2) //program
76
Exceptions Handling
3) Output:
***** Welcome to Stack operations ****
StackException: overflow
Top of MyStack : Learn it
Popping data...
Learn it
Good for all
1.4
Java
Hi
77