Any unwanted, unexpected event disturbed the normal flow of
program called exception
Purpose of exception?
Grace full termination of the program
Exception handling?
Having alternate way to continue rest of the program called
the Exception Handling.
Runtime Stack mechanism?
For every thread JVM will create a run time stack. Each and
every method call performed will be store in the corresponding stack. Each
entry in the stack called stack frame or activation record after completing
every method called and remove from stack. after completing every method empty
stack will delete by JVM
Default handling exception
Inside a method if in any exception occurs, the method in which rise that he the
responsible to create exception object by including flowing information
a>name of exception b>description
of exception c>location at which exception occurs (Stack trace)
After creating exception object method hand over the object
to jvm. Jvm will check whether the method check any exception handling code or
not. If the method does not have exception of code then jvm terminate method
abnormal .and remove corresponding the stack . Then jvm identified the caller
method and check exception handling or not. if not handling then
Difference Between Exception and Error
1.Exception most of the time exception are caused by our
program under these are recoverable
2>Error most of the time error are not caused by our
program and these are due to lack of system resources. Error are non
recoverable .
Checked Exception Vs Unchecked Exception:
The exception which are checked by compiler for smooth
execution of program at run time this exception are default consider as checked
exception
Example FileNotFoundException
public class Test{
public static void
main(String …args){
PrintWriter
p=new PrintWriter(“abc.txt”);
p.print(“Hello”);
}
}
Got exception
Unchecked Exception:
There are some exception which are not checked by compiler,
whether programmer handling or not such
type exceptions are called unchecked exception
Example
ArithmaticException, BomBlastException etc.
public class Test{
public static void
main(String …args) throws ClassNotFoundException{
PrintWriter
p=new PrintWriter(“abc.txt”);
p.print(“Hello”);
}
}
N.B whether it is check or uncheck every exception occurs at
Runtime only there have no chance occurring at compile.
2.RuntimeException and its child classes ,error and its
child class are unchecked exception
Fully Checked vs Partially Checked
Checked is said to be fully checked if only if all its child class also checked example
IOException, InteruptedException
A checked exception is said to be if one only if some of its
child classes are unchecked example exception, throwable
N.B the only possible
the partial checked exceptions are 1> Exception 2> throwable
Exception print how many way?
3 way
a> e.printStackStrace();
b>sop(e) or sop(e.toString())
c>sop(e.getMessage());
Twrowalble class are define the flowing the method to print
the exception information
Method printable
format
printStackStrace() name of exception
: description
at
stack trace
toString() name
of exception : description
getMessage() description
Example:
Public class Test{
Public static void main(String …args){
Try{
Sop(10/0);
}catch(ArithemeaticException e){
e.printStackTrace();
Syso(e); or
syso(e.toString());
Syso(e.getMessage());
}
}
}
Out put:
Java.lang.ArithmeticException : / by zero
at Test main();
Java.lang.ArithmeticException : / by zero
/ by zero
Final:
Final is the modifier applicable for classes, method and
variables. If a class declared as final then we can’t extend that the class.
i.e we can’t create child class for that class i.e inheritance is not possible
for final classes.
If a method is final then we can’t override that method in
child class
If a variable declared then we can’t perform reassignment
that variable
Finally
Finnally is block always associated with try catch to
maintain clean up code
Try{
Risky code
}catch(Exception e){
Exception handling code
}
Finally {
Clean up code
}
The spciality of finally block is it will be executed always
respective of wheather exception rie or not rise or handled or not handled this
about finally block
Finalized
Finalized is a method always invoked by gc just before
destroying object to perform clean up activities Once finalized method complete immediately gc
destroy that object
N.B Finally block is responsible to perform clean up related
to try block i.e what ever resource we open at the part of try block will be
inside finally block
Where as finalized method is responsible to perform clean up
activities related to object i.e what ever resource associated with object will
be dislocated before destroying an object by using finalized object
Various possible of Try catch of finally
In try, catch, finally order is important
When ever we are write try compulsory we should right catch
or finally other wise we will get compile time get error i.e try without catch
or finally is invalid
When ever righting catch compulsory try block must be
required i.e catch with out try is invalid
When ever we writing finally compulsory we should write try
block i.e finally with out try is invalid
Inside try catch finally we can decelerated i.e that is
nesting of try catch finally is allowed
For try catch and finally block curly braces are mandatory
Throw
Throw statement throw key word
kartik (programmer)
throw exception-----------Ã JVM is catch
this exception
Simple Example
Class Test{
Public static void main(String ..args){
Syso(10/0);
}
}
If any one not handle that time which method generate the
exception he is the responsible to call the JVM with location description for
handover all of the information. After JVM will do the postmortem. And give
console print. So by default e.printStackTrace() is there in throwable class.
Output:
Exception in thread “main”
java.lang.ArithmethicException : /
by zero
at Test.main(Test.java :4)
throw key word used?
Some time we can create exception object explicitly and we
can handover in manually for this we have to used throw key word
throw new ArithmethicExcption(“/ by zero”);
Where throw keyword
is handover our manual creation object to JVM
Hance the flowing two program is same
Public class Test{
Public static void main(String ..args){
Syso(10/0);
}}
Output
Exception in thread “main”
java.lang.ArithmethicException :
/ by zero
at
Test.main(Test.java :4)
N.B in this case
main method is responsible to create exception object and handover to
the JVM
|
Public class Test{
Public static void main(String ..args){
throw new ArithematicException(“/ by zero for
explicitly”);
}}
Out put
Exception in thread “main”
java.lang.ArithmethicException :
/ by zero for explicitly
at
Test.main(Test.java :4)
N.B in this case programmer is responsible to create Exception
object explicitly and handover to JVM manually.
|
Best use of throw key word is user define exception or
customized exception
a>
Public class Test{
Public static void main(String ..args){
Syso(10/0);
Syso(“Hello”);
}}
Output
Exception in thread “main”
java.lang.ArithmethicException :
/ by zero
|
Public class Test{
Public static void main(String ..args){
throw new ArithmeticException(“/ by zero”);
Syso(“Hello”);
}}
Output
Test.java line 3 : unreacheable ,….
|
After throw statement we are not allowed to any statement
directly other wise we get compile time error saying Unreachable statement
b>
Public class Test{
Public static void main(String ..args){
throw new Test();
}}
Output
Get compile time exception
Incompatibility type
Found: Test
Required :java.lang.throwable
|
Public class Test extend RunTimeException{
Public static void main(String ..args){
throw new Test();
}}
Output
Getting run time exception
Exception in thread “main”
Test
at
Test.main(Test.java:3)
|
After throw statement we are not allowed to any statement
directly other wise we get
We can use throw key word only for throw able type if we
using normal java object we will get compile time error saying in compatible
type.
Throws keyword:
In our program if there is a possibility of rising checked
exception then compulsory we should handle the checked exception other wise we
get the compile time error saying
Unreported exception XXX must be caught or declared to be
thrown
Import Java.io.*;
Public class Test{
Public static void main(String ..args){
Printwriter pw=new
PrintWriter(“abc.txt”);
Pw.print(“Hello”);
}
}
Out put
Compile time
Test.java:4 : Unreported exception
java.io.FileNotFoundException must be caught or declared to be thrown
Printwriter pw=new PrintWriter(“abc.txt”);
^
Error.
Example 2
Public class Test{
Public static void main(String ..args){
Thread.sleep(1000);
}
}
Out put
Compile time
Test.java:3 : Unreported exception
java.lang.InteruptedException must be caught or declared to be thrown
Thread.sleep(1000);
^
Error.
Example using Try catch
Public class Test{
Public static void main(String ..args){
Try{
Thread.sleep(1000);
}catch(InteruptttedException e ){
}
}
}
Example using throws key word
a>Throws key word to delegate the responsible of error
handling to caller(it may be another method or JVM) then caller method is
responsible to handle that exception.
Public class Test {
Public static void main(String..args) throws InterruptedException {
Thread.sleep(1000);
}
}
b>Throws key required only for checked exception and use
of throws key words unchecked exception there is no use or no impact
c>Throws keyword use only for convince to compiler. Use
of throws key doesn’t prevent abnormal termination of the program.
Example
Public class Test {
Public static void main(String..args) throws InterruptedException {
doStuff();
}
Public static void doStuff() throws InterruptedException{
doMoreStuff();
}
Public static void doMoreStuff() throws InterruptedException{
Thread.sleep(1000);
}
}
N.B It is recommended to use try catch over throws key word
Case 1>
We can use throws key word in method and constructor not for
classes
Public class Test throws Exception {// this is wrong
Public Test() throws Exception { //this correct
}
Public void m1()throws Exception{//this correct
}
}
Case 2
We can use throws key word only for throw able type if we
are trying to use for normal java class the we get compile time error saying
incompatibility type error
But class test extend
RunTimeException
Public class Test{
Public static void main(String ..args){
throw new Test();
}}
Output
Get compile time exception
Incompatibility type
Found: Test
Required :java.lang.throwable
|
Public class Test extend RunTimeException{
Public static void main(String ..args){
throw new Test();
}}
Output
Getting run time exception
Exception in thread “main”
Test
at
Test.main(Test.java:3)
|
Case 3>
Public class Test{
Public static void main(String ..args){
throw new
Exception();
}}
Because Exception is checked exception
Output
Get compile time exception
Test.java:3 : Unreported exception java.io.Exception must
be caught or declared to be thrown
throw new Exception();
^
Error.
|
Public class Test {
Public static void main(String ..args){
throw new Error();
}}
Because Error is unchecked exception
Output
Getting run time exception
Exception in thread “main”
java.lang.Error
at
Test.main(Test.java:3)
|
Case 4>
With in the try block if there no chance of rising an
exception then we can’t write catch block for that exception other wise we will
get compile time error saying Exception XXX is never thrown in body of
corresponding try statement but this rule is applicable for fully check
exception.
Example:
Public class Test{
Public static void main(String ..args){
Syso(“Hello”);
}catch(ArithmeticException e){
}}
Output:
Hello
|
Public class Test{
Public static void main(String ..args){
Syso(“Hello”);
}catch(Exception e){
}}
Output
Hello
|
Public class Test{
Public static void main(String ..args){
Syso(“Hello”);
}catch(IOException e){
}}
Output
Test.Java: 9 java.lang.IOException is never thrown in body
of corresponding try statement
catch(IOException e)
^
Error
but this rule is applicable for fully check exception
|
Public class Test{
Public static void main(String ..args){
Syso(“Hello”);
}catch(InturreptedException e){
}}
Output:
Test.Java: 9 java.lang.IOException is never thrown in body
of corresponding try statement
catch(InturreptedException e)
^
Error
but this rule is applicable
for fully check exception
|
Public class Test{
Public static void main(String ..args){
Syso(“Hello”);
}catch(Error e){
}}
Output
Hello
|
throw
|
thorws
|
To handover our created Exception object to JVM manually
|
Throws key word to delegate the responsible of error
handling to caller(it may be another method or JVM) then caller method is
responsible to handle that exception
|
Remind:
a>try: to maintain
the risky code
b>catch: to maintain exception handling code
c>finally: to maintain clean up code
d>throw: to handover our created Exception object to JVM
manually
e>throws: to delegate the responsible of exception
handling to caller
f>thrown: no such key word in java
Various possible Compile time errors in Exception Handling
1>When checked exception are not handling then we will
get like
Test.java:3 :
Unreported exception java.io.Exception must be caught or declared to be thrown
throw new Exception();
^
Error.
2>When we use multiple catch block and first use
Exception after then use ArithemeticException then you got below exception?
Test.java:3 : java.lang.ArithematicException already bean
caught
3> Test.Java: 9 java.lang.IOException is never thrown in
body of corresponding try statement
catch(IOException e)
^
Error
4> when we used after throw any other statement then we
get : unreachable Statement
5> Incompatibility type
Found: Test
Required :java.lang.throwable
6>try without catch or finally
7>catch with out try
8>finally without try
Customized:
Some times to meet to programming requirement we can define
our own exception is called customized or user define exception
It is highly recommended to define customized exception as
unchecked i.e we have to extended RunTimeException but not exception
How you will do the Checked Exception to unchecked
Exception?
Example
class BelowAgeException extends RuntimeException
{
BelowAgeException(String s){
super(s);
}
}
class OldAgeException extends RuntimeException
{
OldAgeException(String s){
super(s);
}
}
class CustException{
public static void main(String .. args){
int age=Integer.parseInt(args[0]);
if(age >60){
throw new OldAgeException(“your age is to old for govt jobs
”);
}else if(age<18){
throw new BelowAgeException (“your age is not eligible for
govt jobs ”);
}else{
System.out.println(“You will get shortly in your mail”);
}
}}
How you will do the UnChecked Exception to Checked
Exception?
class BelowAgeException extends Exception
{
BelowAgeException(String s){
super(s);
}
}
class OldAgeException extends Exception
{
OldAgeException(String s){
super(s);
}
}
class CustException{
public static void main(String .. args) throws Exception{
int age=Integer.parseInt(args[0]);
if(age >60){
throw new OldAgeException(“your age is to old for govt jobs
”);
}else if(age<18){
throw new BelowAgeException (“your age is not eligible for
govt jobs ”);
}else{
System.out.println(“You will get shortly in your mail”);
}
}}
N.B throw keyword is best suitable for Customized Exception
or User defined Exception but not for Predefine exceptions.
Top 10 exception?
Based on the person who is the rising the exception all
exception are divided into 2 categories
- JVM exception
- Programmatically exception
- Programmer
- API developer
IllegalSateException it is the child class of
RuntimeException and also unchecked exception raised by programmer to indicate
that a has been invoked at run time after starting we are not second starting
otherwise we get IllegalSateException
Thread t =new thread();
t.start(); //valid
t.start(); // IllegalSateException
AssertionError
It is the child class of error hence this unchecked raised
that explicitly by the programmer or API developer to indicate the assert
statement fails.
AssertionError()
Exceptio/Error
|
Raised By
|
|
1-6 Raised by JVM
and 7-10 raised by Programmer or API developer
|
Try With resource in JDK 1.7 Example
Until 1.6 versions it is highly recommended to finally block
to closed resource which are open at the part of try block
But 1.7 versions finally is not required.
JDK 1.6
|
JDK 1.7
|
InputStream is = null; try { is = new FileInputStream("test"); is.read(); ... } catch (Exception e) { ... } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); ... } } |
try (InputStream is = new FileInputStream("test")) { is.read(); ... } catch(Exception e) { ... } //no need to add code to close InputStream //it's close method will be internally called //No need to write finally block
|
Try with multiple
resources
We can declared multiple resource using semicolon
Like
try(r1;r2;r3){
}catch(){
}
Example
try(FileWrite fw=new FileWrite(“Output.txt”); FileReader
fr=new FileReader(“input.txt”)){
}catch(){
}
All resource reference variable are implicitly final hence
with in try block we can’t performed reassignment otherwise we will get compile
error
Example:
1>
try(FileWrite fw=new FileWrite(“Output.txt”)){
fw=new FileWrite(“Output1.txt”))//get excption
}catch(){
}
Uto_closeable resource may not be assignment
2>
try(FileWrite fw=new FileWrite(“Output.txt”)){
//fw=new FileWrite(“Output1.txt”))//get excption
}catch(){
}
Until 1.6 version try should be associated with either catch
or finally but from 1.7 version own words we can take only try with resource
without finally or catch
The main advantage is of try with resource is we are not
required finally block explicitly because we are not required to closed hence
until 1.6 version finally block is hero but 1.7 onwards it is dummy and become
or zero.
Multi catch block
Jdk1.6
|
Jdk 1.7
|
try{
}catch(AE e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}catch(NPE e){
Syso(e.getMessage());
}catch(InturreptedException e){
e.getMessage();
}
}
|
try{
}catch(AE | IOException e){
e.printStackTrace();
} catch(NPE | InturreptedException e){
Syso(e.getMessage());
}
}
|
In multi catch block there should not be any relation betn
exception types (Either Child to parent or Parent to child or same type other wise we will get
compiler time error)
Example A
try{
int i=10/0;
String s=null;
Sop(s.length());
}catch(AE | NPE | Exception e){
Sop(e.getMessage());
}
Get compile time Exception:
Alternatives in multi-catch statement can not be related by
subclass
catch(AE |
NPE | Exception e)
^
Error.
Example B
try{
int i=10/0;
String s=null;
Sop(s.length());
}catch(AE | NPE e){
Sop(e.getMessage());
}
This is give run time error.
Exception propagation?
Inside a method if a exception raised that and if we are not
handling that exception then exception object will be propagated to caller then
caller method is responsible the handle exception. This process is called
exception propagation.
How you will covert one exception to another exception (re-throwing
exception)?
try{
int i=20/0;
}catch(AE e){
throw new NullPointerException();
}