EXCEPTION HANDLING
Introduction
It is an unexpected unwanted event
which disturbs entire flow of the program. RealTimeExample:
1)
SleepingException
2)
TirePuncharedException
If we are not handling exception,
the program may terminate abnormally with out releasing allocated resources.
This is not a graceful termination. Being a good programming practice
compulsory we should handle exceptions for graceful termination of the program.
Exception handling means it is not
repairing an exception we are providing alternative way to continue the program
normally. For example if out programming requirement is to read the data from
London file, if at runtime London file is not available, we have to provide a
local file as the part of exception handling. So that respect of the program
will be continued normally.
Runtime Stack Mechanism
For every thread JVM will create a
runtime stack. All the method calls performed by the thread will be sorted in
the corresponding runtime stack. If a method terminates normally the corresponding
entry from the stack will be removed. After completing all the method calls the
stack is empty. Just before terminating the thread JVM will destroy
the corresponding stack.
Ex:
class ExceptionDemo
{
public
static void main(String[] args)
{
doStuff();
}
public
static void doStuff()
{
doMoreStuff();
}
public
static void doMoreStuff()
{
System.out.println("Hi
this is Exception ...........Thread");
}
}
Default Exception Handling
Ex:
class ExceptionDemo
{
public
static void main(String[] args)
{
doStuff();
}
public
static void doStuff()
{
doMoreStuff();
}
public
static void doMoreStuff()
{
System.out.println(10/0);
}
}
O/P:-
Exception
in thread “main” java.lang.ArithmeticException: /by zero
At
ExceptionDemo.doMoreStuff(ExceptionDemo.java:30)
At ExceptionDemo.doStuff(ExceptionDemo.java:25)
At
ExceptionDemo.main(ExceptionDemo.java:21)
exception object by including the
following information Name of Exception. Description. Location of Exception. After
preparation of Exception Object, The method handovers the object to the JVM,
JVM will check for Exception handling code in that method if the method doesn’t
contain any exception handling code then JVM terminates that method abnormally
and removes corresponding entry from the stack.
JVM will check for exception
handling code in the caller and if the caller method also doesn’t contain exception
handling code then JVM terminates that caller method abnormally and removes
corresponding
entry from the stack. This process
will be continued until main method and if the main method also doesn’t contain
any exception handling code then JVM terminates main method abnormally. Just
before terminating the program JVM handovers the responsibilities of exception
handling to default exception handler. Default exception handler prints the
error in the following format.
Name of Exception : Description
stackTrace
Exception Hierarchy
Throwable is the parent of entire
java exception hierarchy. It has 2 child classes
1)
Exception.
2) Error.
Exception
These are recoverable. Most of the
cases exceptions are raised due to program code only.
Error
Errors are non-recoverable. Most of
the cases errors are due to lack of system resources but not due to our
programs.
Checked Vs UnChecked
The Exceptions which are checked by
the compiler for smooth execution of the program at runtime are called ‘checked
exception’
Ex:-
IOException, ServletException, InterruptedException.
The Exceptions which are unable to
checked by the compiler are called ‘unchecked exceptions’
Runtimeexception and it’s child classes, Error
and it’s child classes are considered as unchecked exceptions and all
the remaining considered as checked.
Whether the exception is checked or
unchecked it always occur at runtime only.
Partially checked Vs fully checked
A checked exception is said to be
fully checked iff all it’s child classes also checked.
Ex:-
IOException.
A checked exception is said to be
partially checked if some of it’s child classes are not checked.
Ex:- Exception, Throwable.(image
here)
Exception Handling By Using try ,catch
We have to place the risky code
inside the try block and the corresponding exception handling code inside catch
block.
try
{
//Risky
code
}
catch (X e)
{
//handling
code
}
Without Exception handling code
class Test class Test
{ {
p.s.v.main(String arg[]) p.s.v.main(String
arg[])
{ {
s.o.p(“Statement 1”);
s.o.p(“statement1”);
s.o.p(10/0); try
s.o.p(“Statement 2”); {
}
s.o.p(“Statement1”);
}
}
catch(ArithmeticException
e)
{
Abnormal termination
s.o.p(10/2);
}
s.o.p(“statement
2”);
}
}
Normal
termination
Control Flow in try, catch
try
{
statement 1;
statement 2;
statement 3;
}
catch (X e)
{
statement 4;
}
statement 5;
Case1: if
there is no exception
1,2,3,5
normal termination.
Case2: if
there is an exception raised at statement 2 and the corresponding catch block
matched. 1,4,5 normal termination.
Case3: if an
exception raised at statement 2 but the corresponding catch block is not
matched 1 Abnormal termination.
Case4: if an
exception raised at statement 4 or statement 5 it is always abnormal
termination.
The Methods to display Exception Information
Throwable class contains the
following methods to display error information.
printStackTrace: It displays error information in
the following format.
Name of
Exception : Description
StackTace.
toString: it
displays error in the following format.
Name of
Exception : Description
getMessage:
it displays error information in the following format.
Description
Ex:-
Class Test
{
public static void main(String arg[])
{
try
{
System.out.println(10/0);
}
catch(ArithmeticException
e)
{
e.printStackTrace();
System.out.println(e.toString());
System.out.println(e.getMessage());
}
}
}
Note: Default Exception handler
always uses printStackTrace method only.
try with multiple catch blocks
The way of handling exception is
valid from exception to exception. Hence for every exception we should define
corresponding catch blocks hence try with multiple catch blocks is possible.
try
{
risky
code
}
catch (ArithmeticException e )
{
//handler
to A.E
}
catch (NullPointerException e)
{
//handler
for N.P.E
}
catch(IOException e)
{
//handler
for IOException
}
catch(Exception e)
{
//handler
for Exception
}
In the case of try with multiple
catch blocks the order of catch blocks is important. And it should be from child
to parent other wise Compiler Error.
Saying Exception xxx has already been caught
Try try
{ {
risky code //risky
code
} }
catch (Exception e ) catch (ArithmeticException e ) e )
{ {}
catch(Exception
e)
} {}
catch (ArithmeticException e)
{
}
C.E java.lang.ArithmeticException
has
already been caught
Note: right code Note:
wrong code
If there is no chance of raising an
exception in try statement then we r not allowed to maintain catch block for
that exception violation leads to compile time error but this rule is
applicable only for fully checked
exceptions.
Try try
{ {
System.out.println("Hi"); System.out.println("Hi");
}
}
catch (ArithmeticException e) catch (Exception e)
{
{
} }
Note: Both are right
code here
Try try
{
{
System.out.println("Hi"); System.out.println("Hi");
} }
catch (IOException e) catch (InterruptedException e)
{
{
}
}
Note: wrong Code
Finally:
It is not recommended to place
cleanup code inside try statement because there is no guarantee for execution
of all statements inside try block.
It is not recommended to maintain
cleanup code with in the catch block because if there is no execution the catch
blocks won’t be executed. We required a block to maintain cleanup code which
should execute always irrespective of whether the exception is raised or not
whether it is handled or not , such block is nothing but “finally block” Hence
the main objective of finally block is to maintain cleanup code.
try
{
//open
the database connection
//read
the data
}
catch (X e)
{
}
finally
{
close the
Connection
}
Ex:
Try
try
{
{
System.out.println("try"); System.out.println(10/0);
}
}
catch (ArithmeticException e) catch (ArithmeticException e)
{
{
System.out.println("catch"); System.out.println("catch");
}
}
finally finally
{ {
System.out.println("finally"); System.out.println("finally");
} }
Hence finally block should always
execute irrespective of whether the execution is raised or not raised or handled
or not handled. The finally block won’t be executed if the system it self
exists(JVM shutdown) i.e in the case of System.exit() finally block won’t be
executed.
try
{
System.out.println("Hi");
System.exit(0);
}
catch (ArithmeticException e)
{
System.out.println("catch");
}
finally
{
System.out.println("finally");
}
O/P:-Hi
Difference Between final, finally, finalize
final: It is
the modifier applicable for classes methods and variables. For final classes we
can’t create child classes i.e inheritance is not possible.
final()
methods can’t be override in child classes for final variables reassignments is
not possible because they are constants.
finally: It
is a block associated with try catch the main objective of finally block is to
maintain cleanup code which should execute always.
finalize: It is a method should be
executed by the “Garbage Collector” just before destroying an object. The main
objective of finalize method is to maintain cleanup code.
Note:- when compared with finalize,
finally is always recommended to maintain cleanup code because there is no
guarantee for the exact behavior of “Garbage Collector” it is Virtual
Machine Dependent.
Control flow in try - catch – finally
The following program will
demonstrates the control flow in different cases.
Ex:
class ExceptionDemo
{
public
static void main(String arg[])
{
try
{
statement1;
statement2;
statement3;
}
catch (X
e)
{
statement4;
}
finally
{
statement5;
}
statement6;
}
}
Case1: if
there is no exception, then the statements 1, 2, 3, 5, 6 will execute with
normal termination.
Case2: if an
exception raised at statement-2 and the corresponding catch block matched, then
the
statements 1, 4, 5, 6 will execute
with normal termination.
Case3: if an
exception raised at statement-2 but the corresponding catch block not matched
then the
statements 1, 5, 6 will execute with
abnormal termination.
Case4: if an
exception raised at statement-2 and while executing the corresponding catch
block at
statement–4 an exception raised then
the statements 1, 5 will execute with abnormal termination.
Case5: if an
exception raised at statement-5 or at statement-6 then it is always abnormal
condition.
Control flow in nested try – catch – finally
The following program will
demonstrates the flow of nested try –catch – finally.
Ex:
try
{
statement
1;
statement
2;
statement
3;
try
{
statement
4;
statement
5;
statement
6;
}
catch (X
e)
{
statement
7;
}
finally
{
statement
8;
}
statement
9;
}
catch (Y
e)
{
statement
10;
}
finally
{
statement
11;
}
statement
12;
Case1: if
there is no exception then the statements 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12
will execute with normal termination.
Case2: if an
exception raised at statement-2 and the corresponding catch block matched then
the statements 1, 10, 11, 12 will execute with normal termination.
Case3: if an
exception raised at statement-2 but the corresponding catch block not matched
then the statements 1, 11, 12 will execute with abnormal termination.
Case4: if an
exception raised at statement-5 and the corresponding inner catch has matched
then the statements 1, 2, 3, 4, 7, 8, 9, 11, 12 will execute with normal
termination.
Case5: if an
exception raised at statement-5 and the inner catch has not matched but outer
catch has matched then the statements 1, 2, 3, 4, 8, 10, 11, 12 will execute
with normal termination.
Case6: if an
exception raised at statement-5 but the inner and outer catch blocks are not
matched then the statements 1, 2, 3, 4, 8, 11 will execute with abnormal
termination.
Case7: if an
exception raised at statement-7 and
i) If outer catch block has matched
then the statements 1, 2, 3, - - - 8, 10, 11, 12 will execute with normal
termination.
ii) If the outer catch block has not
matched then the statements 1, 2, 3, - - - 8, 11 will execute with abnormal
termination.
Case8: if an
exception raised at statement-8 and
i) If outer catch has matched then
the statements 1, 2, 3, - - - will execute with normal termination.
ii) If outer catch has not matched
then the statements 1, 2, 3, - - - 11 will execute with abnormal termination.
Case9: if an
exception raised at statement-9 and
i) If the outer catch has matched
then the statements 1, 2, 3 - - -8, 10, 11, 12 will execute with normal
termination.
ii) If the outer catch has not
matched then the statements 1, 2, 3 - - -8, 11 will execute with abnormal
termination.
Case10: if
an exception raised at statement-10 it is always abnormal termination but
before termination compulsory the finally block should be executed.
Case11: if
an exception raised at statement-11 or 12 it is always abnormal termination.
throw keyword
By using throw we can hand – over
exception object to the JVM. The out put of the following two programs is same.
1)class Test
{
public
static void main(String arg[])
{
System.out.println(10/0);
}
}
2)class Test
{
public
static void main(String arg[])
{
throw
new ArithmeticException ("/ by zero...!");
}
}
Here in first case main method
is responsible for the creation of exception object and hand – over that object
to the JVM.
In the second case we created
object explicitly and hand – over that object to the JVM programmatically by throw
key – word.
Syntax:
throw
e;
Where ‘e’
à Any throwable object
1)
Class Test
{
public
static void main(String arg[])
{
throw
new Test();
}
}
C.E:
ExceptionDemo.java:217: incompatible
types
Found : Test
Required: java.lang.Throwable
Throw new Test();
^
2)
class Test extends RuntimeException
{
public
static void main(String arg[])
{
throw
new Test();
}
}
R.E:Exception in thread “main” Test
At
Test.main(ExceptionDemo.java:217)
3)
class Test
{
static
ArithmeticException e = new ArithmeticException();
public
static void main(String arg[])
{
throw
e;
}
}
R.E:Exception in thread “main”
java.lang.ArithmeticException: / by zero at Test.main(ExceptionDemo.java:225)
Here Explicitly we created a object
to the ArithmeticExcption class and that object was thrown by thow to
the JVM.
4)
class Test
{
static
ArithmeticException e;
public
static void main(String arg[])
{
throw
e;
}
}
R.E:Exception in thread “main”
java.lang.NullPointerException
At
Test.main(ExceptionDemo.java:235)
Here we didn’t create Object to the
AritmeticExcepiton class just we created a reference, so reference variable is
not pointing to any object and we thrown only reference variable that’s why
only it shows
NullPointerException.
After throw keyword we are not
allowed to place any statements directly other wise compile time error.
Ex:
class Test
{
public
static void main(String arg[])
{
throw
new ArithmeticException();
System.out.println("After
throw statement...!");
}
}
C.E:ExceptionDemo.java:244: unreachable
statement
System.out.prntln(“After
throw statement…..!”);
^
Directly in the sense indirectly we
can place any statements after throw. See the following example.
Ex:
class Test
{
public static void main(String
arg[])
{
if(false)
{
throw
new ArithmeticException();
}
else
{
System.out.println("After throw
statement...!");
}
}
}
throws
If our code may be a chance of
raising checked exception then compulsory we should handle that checked exception
either by using try, catch or we have to delegate that responsibility to the
caller using throws
keyword other wise C.E saying UnreportedException
: XXXException must be caught or declared to be thrown
Ex:
class Test
{
public
static void main(String arg[])
{
Thread.sleep(1000);
}
}
We can resolve this problem either
by using try catch or by using throws keyword as follows
Hence the main objective of throws
keyword is to delegate the responsibilities of exception handling to the caller.
Ex:
class Test
{
public static void main(String arg[]) throws
InterruptedException
{
doStuff();
}
public static void doStuff() throws
InterruptedException
{
doMoreStuff();
}
public static void doMoreStuff()
throws InterruptedException
{
Thread.sleep(500);
System.out.println("I am in office");
}
}
If we are not taking at least one
throws keyword we will get Compiler Error. If the parent class constructor
throws some checked exception then the child class constructor must throw same
checked exception or its parent other wise compiler error.
class Test
{
public
static void main(String arg[])
{
try
{
Thread.sleep(1000);
}
catch
(InterruptedException e)
{
}
}
}
No comments:
Post a Comment