6 Exception Handlingpdfnew
6 Exception Handlingpdfnew
Exception: An unwanted unexpected event that disturbs normal flow of the program
is called exception.
Example:
FileNotFoundException
Example: Suppose our programming requirement is to read data from remote file
locating at London. At runtime if London file is not available then our program
should not be terminated abnormally.
We have to provide a local file to continue rest of the program normally. This way of
defining alternative is nothing but exception handling.
Example:
try {
read data from London file
} catch(FileNotFoundException
e)
{ use local file and continue rest of the program
normally
}
After completing every method call JVM removes the corresponding entry from the
stack.
After completing all method calls JVM destroys the empty stack and terminates the
program normally.
Diagram:
Exception Hierarchy:
Ex : If FileNotFoundException occurs then we can use local file and we can continue
rest of the program execution normally.
Error:
Most of the cases errors are not caused by our program these are due to lack of
system resources and these are non-recoverable.
Note:RuntimeException and its child classes, Error and its child classes are
unchecked and all the remaining are considered as checked exceptions.
Note: Whether exception is checked or unchecked compulsory it should occurs at
runtime only and there is no chance of occurring any exception at compile time.
A checked exception is said to be fully checked if and only if all its child classes are
also checked. Example:
1) IOException
2) InterruptedException
A checked exception is said to be partially checked if and only if some of its child
classes are unchecked.
Example:
Exception
1. RuntimeException-----unchecked
2. Error-----unchecked
3. IOException-----fully checked
4. Exception-----partially checked
5. InterruptedException-----fully checked
6. Throwable------partially checked
7. ArithmeticException ----- unchecked
8. NullPointerException ------ unchecked
9. FileNotFoundException ----- fully checked
Diagram:
try{ statement1;
statement2;
statement3;
} catch(X e)
{
statement4;
} statement5;
1, 4, 5 normal termination.
Note:
1. Within the try block if anywhere an exception raised then rest of the try block
won't be executed even though we handled that exception. Hence we have to
place/take only risk code inside try block and length of the try block should be as
less as possible.
2. If any statement which raises an exception and it is not part of any try block then
it is always abnormal termination of the program.
3. There may be a chance of raising an exception inside catch and finally blocks also
in addition to try block.
Various methods to print exception information:
Throwable class defines the following methods to print exception information to the
console.
This method prints exception information in the following
format.
printStackTrace():
Name of the exception: description of exception
Stack trace
This method prints exception information in the following
toString(): format.
Name of the exception: description of exception
This method returns only description of the exception.
getMessage():
Description.
Example:
Example:
try
{
.
.
. .
catch(FileNotFoundException
try e)
{ {
. use local file
. }
. catch(ArithmeticException e)
. { perform these Arithmetic
} operations
catch(Exception e) }
{ catch(SQLException e)
default handler {
} don't use oracle db, use mysqldb
} catch(Exception
e)
{
default handler
}
Example:
class Test
class Test
{
{
public static void
public static void main(String[] args)
main(String[] args)
{ tr
{ tr
y y
{ {
System.out.println(10/0); System.out.println(10/0);
} }
catch(Exception e) catch(ArithmeticException e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
catch(ArithmeticException e)
catch(Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
}}}
}}}
CE:exception
Output:
java.lang.ArithmeticException
Compile successfully.
has already been caught
Finally block:
• It is not recommended to take clean up code inside try block because there is no
guarantee for the execution of every statement inside a try.
• It is not recommended to place clean up code inside catch block because if there
is no exception then catch block won't be executed.
• We require some place to maintain clean up code which should be executed
always irrespective of whether exception raised or not raised and whether
handled or not handled. Such type of best place is nothing but finally block.
• Hence the main objective of finally block is to maintain cleanup code.
Example:
try
{
risky code
}
catch(x e)
{
handling code
}
finally
{
cleanup code
}
The speciality of finally block is it will be executed always irrespective of whether the
exception raised or not raised and whether handled or not handled.
class
Test
{ public static void main(String[] args)
{ tr
y
{
System.out.println("try block executed");
}
catch(ArithmeticException e)
{
System.out.println("catch block executed");
}
finally
{
System.out.println("finally block
executed"); }
}
} Output:
try block executed
Finally block executed
Case-2: If an exception raised but the corresponding catch
block matched:
class
Test
{ public static void main(String[] args)
{ tr
y
{
System.out.println("try block executed");
System.out.println(10/0);
}
catch(ArithmeticException e)
{
System.out.println("catch block executed");
}
finally
{
System.out.println("finally block executed");
}
}
} Output:
Try block executed
Catch block executed
Finally block executed
class Test
{ public static void main(String[] args)
{ tr
y
{
System.out.println("try block executed");
System.out.println(10/0);
}
catch(NullPointerException e)
{
System.out.println("catch block executed");
}
finally
{
System.out.println("finally block executed");
}
}
} Output:
Try block executed
Finally block executed
Exception in thread "main" java.lang.ArithmeticException: / by
zero atTest.main(Test.java:8)
return Vs finally:
Even though return statement present in try or catch blocks first finally will be
executed and after that only return statement will be considered. i.efinally block
dominates return statement.
Example:
class
Test {
public static void main(String[] args)
{ try
{
System.out.println("try block
executed"); return; }
catch(ArithmeticException e)
{
System.out.println("catch block executed");
}
finally
{
System.out.println("finally block executed");
} }}
Output
:
try block executed
Finally block executed
If return statement present try, catch and finally blocks then finally block return
statement will be considered.
Example:
class
Test {
public static void main(String[] args)
{
System.out.println(m1());
}
public static intm1()
{ try
{
System.out.println(10/0)
; return 777; }
catch(ArithmeticException e)
{ return
888; }
finally{ r
eturn 999;
} }}
Output
:
999
finally vs System.exit(0):
==========================
There is only one situation where the finally block won't be executed is whenever we
are using System.exit(0) method.
When ever we are using System.exit(0) then JVM itself will be shutdown , in this case
finally block won't be executed.
Example:
class Test
{
public static void main(String[] args)
{ try
{
System.out.println("try");
System.exit(0);
}
catch(ArithmeticException e)
{
System.out.println("catch block executed");
}
finally
{
System.out.println("finally block executed");
} }}
Output
: try
Note : System.exit(0);
1. This argument acts as status code. Insteadof zero, we can take any integer value
2. zero means normal termination , non-zero means abnormal termination
3. This status code internally used by JVM, whether it is zero or non-zero there is no
change in the result and effect is same wrt program.
final:
finally:
• finally is the block always associated with try-catch to maintain clean up code
which should be executed always irrespective of whether exception raised or
not raised and whether handled or not handled.
finalize:
Note:
1. finally block meant for cleanup activities related to try block where as
finalize() method meant for cleanup activities related to object.
Example:
try
{
Stmt 1;
Stmt-2;
Stmt-3;
}
catch(Exception e)
{
Stmt-4;
}
finally
{
stmt-5;
}
Stmt-6;
try
{
stmt-1;
stmt-2;
stmt-3; try
{ stmt-4;
stmt-5;
stmt-6;
} catch (X
e)
{ stmt-7;
} finally
{ stmt-8;
} stmt-9;
} catch (Y
e)
{
stmt-10;
}
finally
{
stmt-11;
}
stmt-12;
Note:
1.if we are not entering into the try block then the finally block won't be executed.
Once we entered into the try block without executing finally block we can't come out.
Note: Default exception handler can handle only one exception at a time and that is
the most recently raised exception.
try {} catch
✔ (X e) {}
try {} catch
(X e) {}
✔ catch (Y e)
{}
try {} catch
(X e) {}
✘ catch (X e) {} //CE:exception ArithmeticException has already been
caught
try {} catch
✔ (X e) {}
finally {}
try {}
✔ finally {}
try {}
catch (X e) {}
✘ System.out.println("Hello");
catch (Y e) {} //CE: 'catch' without 'try'
try {}
catch (X e) {}
System.out.println("Hello");
✘ finally {} //CE: 'finally' without
'try'
try {}
finally {}
catch (X e) {} //CE: 'catch' without 'try'
✘
try {} catch
(X e) {}
✔ try {}
finally {}
try {} catch
(X e) {}
✘ finally {}
finally {} //CE: 'finally' without 'try'
try {} catch
(X e) { try {}
✔ catch (Y e1) {}
}
try {} catch (X
e) {} finally
{ try {} catch
✔ (Y e1) {}
finally {}
}
try {
try {} //CE: 'try' without 'catch', 'finally' or resource declarations
✘ }
catch (X e) {}
try {}
catch (X e) //CE:'{' expected
✘ System.out.println("Hello");
try {}
catch (NullPointerException e1) {}
✘ finally //CE: '{' expected
System.out.println("Hello");
throw statement:
Sometimes we can create Exception object explicitly and we can hand over to the JVM
manually by using throw keyword.
Example:
Case 1:
throw e;
Case 2:
After throw statement we can't take any statement directly otherwise we will get
compile time error saying unreachable statement.
Example:
class Test3
{ class Test3
public static void main(String[] {
args){ public static void main(String[]
System.out.println(10/0); args){ throw new
System.out.println("hello"); ArithmeticException("/ by zero");
} System.out.println("hello");
} }
Output: }
Runtime error: Exception in thread Output:
"main" Compile time error.
java.lang.ArithmeticException: / by Test3.java:5: unreachable statement
zero at System.out.println("hello");
Test3.main(Test3.java:4)
Case 3:
We can use throw keyword only for Throwable types otherwise we will get compile
time error saying incomputable types.
Example:
class Test3 class Test3 extends RuntimeException
{ {
public static void main(String[] public static void main(String[] args){
args){ throw new Test3();
throw new Test3(); }
} }
}Output: Output:
Compile time error. Runtime error: Exception in thread
Test3.java:4: incompatible "main" Test3 at
types found : Test3 required:
java.lang.Throwable throw new Test3.main(Test3.java:4)
Test3();
Throws statement:
In our program if there is any chance of raising checked exception then compulsory
we should handle either by try catch or by throws keyword otherwise the code won't
compile.
Example: import
java.io.*; class
Test3 {
public static void main(String[] args)
{ PrinterWriter out=new PrintWriter("abc.txt");
out.println("hello");
}
}
CE :
Unreported exception java.io.FileNotFoundException; must be caught or
declared to be thrown.
Example:
class
Test3 {
public static void main(String[] args){
Thread.sleep(5000);
}
}
Example:
By using try catch By using throws keyword
We can use throws keyword to delegate the
class Test3 responsibility of exception handling to the caller
{ method. Then caller method is responsible to
public static void handle that exception.
main(String[] args){ try{ class Test3
Thread.sleep(5000); {
} public static void main(String[] args)throws
catch(InterruptedException
e){} } InterruptedException{
}
Thread.sleep(5000);
Output:
}
Compile and running
}
successfully
Output:
Compile and running successfully
Note :
Output:
Compile and running successfully.
In the above program if we are removing at least one throws keyword then the
program won't compile.
Case 1: we can use throws keyword only for Throwable types otherwise we will get
compile time error saying incompatible types.
Example:
class Test3{
public static void main(String[]
args)
throws Test3 class Test3 extends RuntimeException{
{} public static void main(String[]
args)
}
throws
Output:
Test3
Compile time error
{}
Test3.java:2: incompatible types
found : Test3 }
required: java.lang.Throwable Output:
public static void Compile and running successfully.
main(String[] args)
throws Test3
Case 2:Example:
class Test3{ public static void
main(String[] args){ throw new class Test3{ public static void
Exception(); main(String[] args){ throw new
} Error();
} }
Output: }
Compile time error. Output:
Test3.java:3: unreported Runtime error
exception Exception in thread "main"
java.lang.Exception; must be java.lang.Error at
caught or declared to be thrown Test3.main(Test3.java:3)
Case 3:
In our program with in the try block, if there is no chance of rising an exception then
we can't right catch block for that exception otherwise we will get compile time error
sayingexception XXX is never thrown in body of corresponding try statement. But this
rule is applicable only for fully checked exception.
Example:
Case 4:
We can use throws keyword only for constructors and methods but not for classes.
Example:
Example:
1. InSufficientFundsException
2. TooYoungException
3. TooOldException
Program: class TooYoungException extends
RuntimeException
{
TooYoungException(String s)
{ super(s);
} }
class TooOldException extends RuntimeException
{
TooOldException(String s)
{ super(s);
} } class
CustomizedExceptionDemo
{
public static void main(String[] args)
{ int age=Integer.parseInt(args[0]);
if(age>60) {
throw new TooYoungException("please wait some more time.... u will get
best match"); }
else if(age<18)
{
throw new TooOldException("u r age already crossed....no chance of
getting married"); } else
{
System.out.println("you will get match details soon by e-
mail"); }}}
Output:
1)E:\scjp>java CustomizedExceptionDemo 61
Exception in thread "main" TooYoungException:
please wait some more time.... u will get best match at
CustomizedExceptionDemo.main(CustomizedExceptionDemo.java:21)
2)E:\scjp>java CustomizedExceptionDemo 27
You will get match details soon by e-mail
3)E:\scjp>java CustomizedExceptionDemo 9
Exception in thread "main" TooOldException:
u r age already crossed....no chance of getting married at
CustomizedExceptionDemo.main(CustomizedExceptionDemo.java:25)
Note: It is highly recommended to maintain our customized exceptions as unchecked
by extending RuntimeException.
We can catch any Throwable type including Errors also.
Example:
Top-10 Exceptions:
Based on the person who is raising exception, all exceptions are divided into two
types.
They are:
1) JVM Exceptions:
2) Programmatic exceptions:
JVM Exceptions:
The exceptions which are raised automatically by the jvm whenever a particular
event occurs, are called JVM Exceptions.
Example:
1) ArrayIndexOutOfBoundsException(AIOOBE)
2) NullPointerException (NPE).
Programmatic Exceptions:
The exceptions which are raised explicitly by the programmer (or) by the API
developer are called programmatic exceptions.
Example: 1) IllegalArgumentException(IAE).
1. ArrayIndexOutOfBoundsException:
It is the child class of RuntimeException and hence it is unchecked. Raised
automatically by the JVM whenever we are trying to access array element with
out of range index. Example:
class Test{ public static void
main(String[] args){ int[] x=new
int[10];
System.out.println(x[0]);//valid
System.out.println(x[100]);//AIOOBE
System.out.println(x[-100]);//AIOOBE
}
}
2. NullPointerException:
3. StackOverFlowError:
It is the child class of Error and hence it is unchecked. Whenever we are trying
to invoke recursive method call JVM will raise StackOverFloeError
automatically.
Example:
class Test
{
public static void methodOne()
{ methodTwo(); } public
static void methodTwo()
{ methodOne()
; }
public static void main(String[] args)
{ methodOne()
;
}
}
Output:
Run time error: StackOverFloeError
4. NoClassDefFoundError:
It is the child class of Error and hence it is unchecked. JVM will raise this error
automatically whenever it is unable to find required .class file. Example: java
Test If Test.class is not available. Then we will get NoClassDefFound error.
5. ClassCastException:
It is the child class of RuntimeException and hence it is unchecked. Raised
automatically by the JVM whenever we are trying to type cast parent object to
child type.
Example:
6. ExceptionInInitializerError:
It is the child class of Error and it is unchecked. Raised automatically by the
JVM, if any exception occurs while performing static variable initialization
and static block execution.
Example 1: class
Test{ static int
i=10/0;
}
Output:
Runtime exception:
Exception in thread "main" java.lang.ExceptionInInitializerError
Example
2: class
Test{ stat
ic {
String s=null;
System.out.println(s.length());
}}
Output:
Runtime exception:
Exception in thread "main" java.lang.ExceptionInInitializerError
7. IllegalArgumentException:
8. NumberFormatException:
9. IllegalStateException:
Example:
Once session expires we can't call any method on the session object otherwise
we will get IllegalStateException
HttpSession session=req.getSession();
System.out.println(session.getId());
session.invalidate();
System.out.println(session.getId()); // illgalstateException
10. AssertionError:
It is the child class of Error and hence it is unchecked. Raised explicitly by the
programmer or by API developer to indicate that Assert statement fails.
Example:
assert(false);
Exception/Error Raised by
1. AIOOBE
2. NPE(NullPointerException)
3. StackOverFlowError Raised automatically by JVM(JVM
4. NoClassDefFoundError Exceptions)
5. CCE(ClassCastException)
6. ExceptionInInitializerError
1. IAE(IllegalArgumentException)
Untill 1.6 version it is highly recommended to write finally block to close all resources
which are open as part of try block.
BufferedReader br=null; try{ br=new
BufferedReader(new FileReader("abc.txt"));
//use br based on our requirements
} catch(IOException
e) {
// handling code
} finally
{ if(br !=
null)
br.close();
} problems in this
approach :
Conclusions:
1. We can declare any no of resources but all these resources should be seperated
with ;(semicolon)
try(R1 ; R2 ; R3)
{
-------------
-------------
}
3. All resource reference variables are implicitly final and hence we can't perform
reassignment with in the try block.
5.The main advantage of "try with resources" is finally block will become dummy
because we are not required to close resources of explicitly.
Until 1.6 version ,Eventhough Multiple Exceptions having same handling code we
have to write a separate catch block for every exceptions, it increases length of the
code and reviews readability
try{
-----------------
-----------------
} catch(ArithmeticException
e) {
e.printStackTrace(); }
catch(NullPointerException e) {
e.printStackTrace(); }
catch(ClassCastException e) {
System.out.println(e.getMessage());
}
catch(IOException e) {
System.out.println(e.getMessage());
}
To overcome this problem Sun People introduced "Multi catch block" concept in 1.7
version.
The main advantage of multi catch block is we can write a single catch block , which
can handle multiple different exceptions try{
-----------------
-----------------
} catch(ArithmeticException | NullPointerException
e) {
e.printStackTrace(); }
catch(ClassCastException | IOException e) {
System.out.println(e.getMessage());
}
In multi catch block, there should not be any relation between Exception
types(either child to parent Or parent to child Or same type , otherwise we will get
Compile time error )
Example:
Exception Propagation :
With in a method if an exception raised and if that method doesn't handle that
exception, then Exception object will be propagated to the caller then caller method
is responsible to handle that exceptions. This process is called Exception
Propagation. Rethrowing an Exception :
To convert the one exception type to another exception type , we can use rethrowing
exception concept.
class Test { public static void
main(String[] args){
try {
System.out.println(10/0);
} catch(ArithmeticException e) {
throw new NullPointerException();
}
} }
output
:
RE:NPE