Exception Handling
Exception Handling
Exception Handling
--------------------
Q)What is the difference between Error and Exception?
------------------------------------------------------
And:
----
Error is a problem in java applications.
There are two types of errors in java.
1.Compile time Errors
2.Runtime Errors
1.Compile time errors:
-----------------------
These are problems identified by the compiler at compilation time.
In general, There are three types of compile time errors.
1.Lexical Errors: Mistakes in keywords,..
EX:int i=10; ----> Valid
nit i=10; ----> Invalid
2.Syntax Errors: Gramatical Mistakes or syntactical mistakes.
EX: int i=10;---> Valid
i int 10 ; --> Invalid
3.Semantic Errors: Providing operators inbetween incompatible types.
EX: int i=10;
int j=20;
int k=i+j; ----> Valid
EX: int i=10;
boolean b=true;
char c= i+b;----> Invalid.
Note: Some other errors are generated by Compiler when we voilate JAVA rules and
regulations in java applications.
EX: Unreachable Statements, valriable might not have been initialization
,possible loss of precision,....
2.Runtime Errors:
------------------
These are the problems for which we are unable to provide solutions programatically
and these errors are not identified by the compilers and these errors are occurred
at runtime.
EX: Insufficient Main Memory.
Unavailability of IO Components.
JVMInternal Problems.
-----
-----
2.Exception:
-------------
Exception is a problem, for which we are able to provide solutions programatically.
EX: ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException
----
-----
------------------------------------------------------------------------
Exception: Exception is an unexpected event occured in java applications at runtime
, which may be provided by users while entering dynamic input in java applications,
provided by the Database Engines while executing sql queries in Jdbc applications,
provided by Network while establish connection between local machine and remote
machine,.....causes abnormal termination to the java applications.
2.Abnormal Termination
-----------------------
Terminating program in the middle is called as Abnormal Termination.
1.Predefined Exceptions
-------------------------
These Exceptions are defined by JAVA programming language and provided along Java
software.
-- Diagram----
Unchecked Exceptions are not recognized at compilation time, these exceptions are
recognized at runtime by JVM.
Note: In Exceptions Arch, RuntimeException and its sub classes and Error and its
sub classes are the examples for Unchecked Exceptions and all the remaining classes
are the examples for Checked Exceptions.
Q)What is the difference between Pure checked exception and Partially Checked
Exceptions?
----------------------------------------------------------------------
Ans:
----
If any checked exception is having only checked exceptions as sub classes then this
exception is called as Pure Checked Exception.
EX: IOException
If any Checked Exception contains atleast one sub class as unchecked exception then
that Checked Exception is called as Partially Checked Exception.
EX: Exception , Throwable
If we run the above program then JVM will provide ArithmeticException with the
following Exception message.
The above exception message is devided into the following three parts.
1.Exception Name: java.lang.ArithmeticException
2.Exception Descrioptioun: / by zero
3.Exception Location : Test.java:7
2.NullPointerException:
------------------------
In java applications, when we access any instance variable and instance methods by
using a reference variable contaiuns null value then JVM will rise
NullPointerException.
EX:
---
class Test
{
public static void main(String[] args)
{
java.util.Date d=null;
System.out.println(d.toString());
}
}
If we run the above code then JVMwill provide the following exception details.
1.Exception Name : java.lang.NullPointerException
2.Exception Description: --- No description----
3.Exception Location: Test.java:6
3.ArrayIndexOutOfBoundsException:
-----------------------------------
In java applications, when we insert an element to an array at a particular index
value and when we are trying to access an element from an array at a particular
index value and if the specified index value is in out side of the arrays size
then JVM will rise an exception like "ArrayIndexOutOfBoundsException".
EX:
---
class Test
{
public static void main(String[] args)
{
int [] a={1,2,3,4,5};
System.out.println(a[10]);
}
}
If we run the above program then JVM will rise an exception with the following
details.
Exception Name : java.lang.ArrayindexOutOfBoundsException
Exception Description: 10
Exception Location: Test.java: 6
4.ClassCastException:
----------------------
In java applications, we are able to keep sub class object reference value in
super class reference variable, but, we are unable to keep super class object
reference value in sub class reference variable. If we are trying to keep super
class object reference value in sub class reference variable then JVM will rise an
exception like "java.lang.ClassCastException".
EX:
---
class A
{
}
class B extends A
{
}
class Test
{
public static void main(String[] args)
{
A a=new A();
B b=(B)a;
}
}
If we run the above code then JVM will rise an exception with the following
details.
Exception Name: java.lang.ClassCastException
Exception Description: A can not be cast to B
Excepttion location: Test.java: 12
5.ClassNotFoundException :
----------------------------
In java applications, if we want to load a particular class bytecode to the memory
with out creating object then we will use the following method from java.lang.Class
class.
When JVM encouter the above code then JVM will search for 0-arg constructor and
non-private constructor in the loaded class. if 0-arg constructor is not
availabnle, if parameterized construcvtor is existed then JVM will rise
"java.lang.instantiationException". If non-private constructor is not available, if
private constructor is available then JVM will rise
"java.lang.IllegalAccessException".
EX1:
---
class A
{
static
{
System.out.println("Class Loading");
}
A(int i)
{
System.out.println("Object Creating");
}
}
class Test
{
public static void main(String[] args) throws Exception
{
Class c=Class.forName("A");
Object obj=c.newInstance();
}
}
If run the above code then JVM will provide an exception with the following
details.
1.Exception Name : java.lang.InstantiationException
2.Exception Description: A
3.Exception Location:Test.java: 17
EX:
---
class A
{
static
{
System.out.println("Class Loading");
}
private A()
{
System.out.println("Object Creating");
}
}
class Test
{
public static void main(String[] args) throws Exception
{
Class c=Class.forName("A");
Object obj=c.newInstance();
}
}
If we run the above code then JVM will rise an exception with the following details
1.Exception Name : java.lang.IllegalAccessException
2.Exception Decrition: Test class can not access the members of class A
with the modifier "private".
3.Exception Location" Test.java: 17
--------------------------------------------------------------------
'throw' keyword:
------------------
'throw' is a java keyword, it can be used to rise exceptions intentionally as per
the developers application requirement.
Syntax:
--------
throw new Exception_Name("----Exception Description-----");
EX:
----
class Test
{
public static void main(String[] args)throws Exception
{
String accNo=args[0];
String accName=args[1];
int pin_Num=Integer.parseInt(args[2]);
String accType=args[3];
System.out.println("Account Details");
System.out.println("---------------------");
System.out.println("Account Number :"+accNo);
System.out.println("Account Name :"+accName);
System.out.println("Account Type :"+accType);
System.out.println("Account PIN Number:"+pin_Num);
if(pin_Num>=1000 && pin_Num<=9999)
{
System.out.println("valid PIN Number");
}
else
{
throw new RuntimeException("Invalid PIN Number, enter Valid 4
digit PIN Number");
}
}
}
D:\javaapps>javac Test.java
D:\javaapps>java Test abc123 AAA 1234 Ssavings
--- Account details with out Exception-----
---Account details----
Exception in thread "main" java.lang.RuntimeException: Invalid PIN Number, enter
valid 4 digit PIN number
at Test.main(Test.java:17)
------------------------------------------------------------------------
1.'throws' keyword:
--------------------
It is a Java keyword,it can be used to bypass the generated exception from the
present method or constructor to the caller method (or) constructor.
Ex:
Void m1() throws NullPointerException,ClassNotFoundException{
}
Status:Valid
Ex:
Void m1() throws IOException,FileNotFoundException
{
}
Status:Valid , Not Suggestible
If we specify any super exception class along with throws keyword,then it is not
necessary to specify any of its child exception classes along with �throws�
keyword.
NOTE:In any Java method,if we call some other method which is bypassing an
exception by using �throws� keyword,then we must handle that exception either by
using �throws� keyword in the present method[Caller Method] prototype or by using
�try-catch-finally� in the body of the present method[Caller method].
Ex:
Void m1() throws Exception{
-----
------
}
Void m2(){
try{
m1();
}
catch(Exception e){
e.printStackTrace();
}
}
EX:
---
void m1() throws Exception{
----
}
void m2() throws Exception{
m1();
}
EX:
---
import java.io.*;
class A{
void add() throws Exception{
concat();
}
Void concat() throws IOException{
throw new IOException();
}
}
class Test{
public static void main(String args[]) throws Throwable{
A a=new A();
a.add();
}
}
Internal Flow:
---------------
If we execute the above program,then JVM will recognize throw keyword in concat()
method and JVM will rise an exception in concat() method, due to throws keyword in
concat() method prototype, Exception will be bypassed to concat() method call that
is in add(), due to throws keyword in add() method Exception will be bypassed to
add() method call , that is , in main() method, Due to 'throws' keyword in main()
method Excepotion will be bypassed to main() method call , that is, to JVM, where
JVM will activate "Default Exception Handler" , where Default Exception Handler
will display exception details.
'throws' keyword is able to by pass the exception from the present method to the
caller method.
try-catch-finally:
--------------------
In Java application �throws� keyword is not really an exception handler,because
�throws� keyword will bypass the exception handling responsibility from present
method to the caller method.
If we want to handle the exceptions,the location where exceptions are generated
then we have to use �try-catch-finally�.
Syntax:
--------
try{
----
}
catch(Exception_Name e){
----
}
finally{
----
}
where the purpose of try block is to include a set of exceptions , which may rise
an exception.
If JVM identify any exception inside "try" block then JVM will bypass flow of
execution to "catch" block by skipping all the remaining instructions in try block
and by passing the generated Exception object reference as parameter.
If no exception is identified in "try" block then JVM will execute completely "try"
block,at the end of try block, JVM will bypass flow of execution to "finally" block
directly.
The main purpose of catch block is to catch the exception from try block and to
display exception details on command prompt.
To display exception details on command prompt,we have to use the following three
approaches.
1.e.printStackTrace()
2.System.out.println(e):
3.System.out.println(e.getMessage());
1.e.printStackTrace():
----------------------
It will display the exception details like Exception Name,Exception Description and
Exception Location.
2.System.out.println(e):
-------------------------
If we pass Exception object reference variable as parameter to
System.out.println(-) method then JVM will access Exception class toString() method
internally,it will display the exception details like Exception name,Exception
description.
3.System.out.println(e.getMessage()):
--------------------------------------
Where getMessage() method will return a String contains the exception details like
only Description of the exception.
EX:
---
class Test{
public static void main(String args[]){
try{
throw new ArithmeticException("My Arithmetic Exception");
}
catch(ArithmeticException e){
e.printStackTrace();
System.out.println();
System.out.println(e);
System.out.println();
System.out.println(e.getMessage());
}
finally{
}
}
}
Output:
------
java.lang.ArithmeticException:My Arithmetic Exception
at Test.main(Test.java:7)
Where the main purpose of finally block is to include some Java code , it will be
executed irrespective of getting exception in "try" block and irrespective of
executing "catch" block.
EX:
---
class Test{
public static void main(String args[]){
System.out.println("Before Try");
try{
System.out.println("Before Exception in try");
float f=100/0;
System.out.println("After Exception in try");
}
catch(Exception e){
System.out.println("Inside Catch");
}
finally{
System.out.println("Inside Finally");
}
System.out.println("After Finally");
}
}
Output:
---------
Before try
Before exception in try
Inside catch
Inside finally
After finally
Q)Find the output from the following program?
-------------------------------------------------
class A{
int m1(){
try{
return 10;
}
catch(Exception e){
return 20;
}
finally{
return 30;
}
}
}
class Test{
public static void main(String args[]){
A a=new A();
int val=a.m1();
System.out.println(val);
}
}
Output:
-------
30
NOTE:finally block provided return statement is the finally return statement for
the method
Reason:When JVM encounter exception in try block,JVM will search for catch block,if
no catch block is identified,then JVM will terminate the program abnormally after
executing finally block.
Syntax-2:
----------
try{
}
catch(Exception e){
try{
}
catch(Exception e)
{
}
finally{
}
}
finally{
}
Syntax-3:
----------
try{
}
catch(Exception e){
}
finally{
try{
}
catch(Exception e){
}
finally{
}
}
Q)Is it possible to provide more than one catch block for a single try block?
-----------------------------------------------------------------------
Ans:
----
Yes,it is possible to provide more than one catch block for a single try block but
with the following conditions.
1.If no inheritance relation existed between exception class names which are
specified along with catch blocks then it is possible to provide all the catch
blocks in any order.If inheritance relation is existed between exception class
names then we have to arrange all the catch blocks as per Exception classes
inheritance increasing order.
2.In general,specifying an exception class along with a catch block is not giving
any guarantee to rise the same exception in the corresponding try block,but if we
specify any pure checked exception along with any catch block then the
corresponding "try" block must rise the same pure checked exception.
Ex1:
----
try{
}
catch(ArithmeticException e){
}
catch(ClassCastException e){
}
catch(NullPointerException e){
}
Status:Valid Combination
Ex2:
----
try{
}
catch(NullPointerException e){
}
catch(ArithmeticException e){
}
catch(ClassCastException e){
}
status:Valid Combination
Ex3:
----
try{
}
catch(ArithmeticException e){
}
catch(RuntimeException e){
}
catch(Exception e){
}
Status:Valid
Ex4:
----
try{
}
catch(Exception e){
}
catch(RuntimeException e){
}
catch(ArithmeticException e){
}
status:Invalid
Ex5:
----
try{
throws new ArithmeticException("My Exception");
}
catch(ArithmeticException e){
}
catch(IOException e){
}
catch(NullPointerException e){
}
Status:Invalid
Ex6:
try{
throw new IOException("My Exception");
}
catch(ArithmeticException e){
}
catch(IOException e){
}
catch(NullPointerException e){
}
status:Valid
try{
throw new MyException("My Custom Exception");
}
catch(MyException me){
me.printStackTrace();
}
try{
}catch(ArithmeticException e){
}catch(NullPointerException e){
}catch(ClassCastException e){
}
Syntax:
-------
try{
}
catch(Exception1 | Exception2 |....|Exception-n e){
}
where Exception1,Exception2....must not have inheritance relation otherwise
Compilation error will be raised.
EX:
---
class Test{
public static void main(String args[]){
try{
/* int a=10;
int b=0;
float c=a/b;
*/
/*java.util.Date d=null;
System.out.println(d.toString());
*/
int[] a={1,2,3,4,5};
System.out.println(a[10]);
}
catch(ArithmeticException | NullPointerException | ArrayIndexOutOfBoundsException
e){
e.printStackTrace();
}
}
Try-With-Resources/Auto Closeable Resources:
---------------------------------------------
In general,in Java applications,we may use the resources like
Files,Streams,Database Connections....as per the application requirements.
The main intention to declare the resources before "try" block is to make available
resources variables to "catch" block and to "finally" block to use.
If we want to close the resources in "finally" block then we have to use close()
methods, which are throwing some exceptions like IOException,SQLException depending
on the resource by using "throws" keyword,to handle these exceptions we have to use
"try-catch-finally" inside "finally" block.
To manage the resources in Java applications,if we use the above convention then
developers have to use close() methods explicitly,Developers have to provide try-
catch-finally inside "finally" block,this convention will increase no.of
instructions in Java applications.
To overcome all the above problems,JAVA7 version has provided a new Feature in the
form of "Try-With-Resources" or "Auto Closeable Resources".
Synatx:
-------
try(Resource1;Resource2;........Resource-n){
-------
------
}
catch(Exception e){
-----
-----
}
Where if we declare resources as AutoCloseable resources along with "try" then the
resources reference variables are converted as "final" variables.
Ex:
---
try(File f=new File("abc.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Connection con=DriverManager.getConnection("jdbc:odbc:nag","system","durga");)
{
-------
-------
}
catch(Exception e){
e.printStackTrace();
}