10.+Exception+Handling
10.+Exception+Handling
Exception
Handling
1 http://youtube.com/durgasoftware
Core Java
Exception Handling
NOTE: Some other errors are generated by Compiler when we violate JAVA rules and
regulations in java applications.
EX: Unreachable Statements, valriable might not have been initialization, possible loss of
precision,....
• Runtime Errors:
These are the problems for which we are unable to provide solutions
programmatically and these errors are not identified by the compilers and these errors
are occurred at runtime.
2 http://youtube.com/durgasoftware
Core Java
2) Exception:
Exception is a problem, for which we are able to provide solutions programmatically.
EX: ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException
----
-----
• Smooth Termination
Terminating program at end is called as Smooth termination.
• Abnormal Termination
Terminating program in the middle is called as Abnormal Termination.
• Java is having very good memory management system in the form of Heap
Memory Management system, it is a dynamic memory management system, it
allocates and deallocates memory for the objects at runtime.
• Java is having very good exception handling mechanisms, JAVA has provided very
good predefined library to represent and handle almost all the frequently
generated exceptions.
3 http://youtube.com/durgasoftware
Core Java
• Predefined Exceptions
These Exceptions are defined by JAVA programming language and provided along Java
software.
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.
4 http://youtube.com/durgasoftware
Core Java
If any Checked Exception contains at least one sub class as unchecked exception then
that Checked Exception is called as Partially Checked Exception.
EX: Exception, Throwable
EX:
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) int i=10;
6) int j=0;
7) float f=i/j;
8) System.out.println(f);
9) }
10) }
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.
• Exception Name: java.lang.ArithmeticException
• Exception Descrioptioun: / by zero
• Exception Location : Test.java:7
5 http://youtube.com/durgasoftware
Core Java
• NullPointerException:
In java applications, when we access any instance variable and instance methods by using
a reference variable contains null value then JVM will rise NullPointerException.
EX:
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) java.util.Date d=null;
6) System.out.println(d.toString());
7) }
8) }
If we run the above code then JVM will provide the following exception details.
• Exception Name: java.lang.NullPointerException
• Exception Description: --- No description----
• Exception Location: Test.java:6
• 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 outside of the arrays size then JVM will rise an exception
like "ArrayIndexOutOfBoundsException".
EX:
1) class Test
2) {
3) public static void main(String[] args)
4) {
5) int [] a={1,2,3,4,5};
6) System.out.println(a[10]);
7) }
8) }
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
6 http://youtube.com/durgasoftware
Core Java
• 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:
1) class A
2) {
3) }
4) class B extends A
5) {
6) }
7) class Test
8) {
9) public static void main(String[] args)
10) {
11) A a=new A();
12) B b=(B)a;
13) }
14) }
If we run the above code then JVM will rise an exception with the following details.
Exception Name: java.lang.ClassCastException
Exception Description: A cannot be cast to B
Exception location: Test.java: 12
• ClassNotFoundException:
In Java applications, if we want to load a particular class byte code to the memory
without creating object then we will use the following method from java.lang.Class
class.
When JVM encounter the above instruction, JVM will search for A.class file at current
location, at java predefined library and at the locations referred by "classpath"
environment variable, if the required A.class file is not identified at all the locations
then JVM will rise ClassNotFoundException.
7 http://youtube.com/durgasoftware
Core Java
EX:
1) class A
2) {
3) static
4) {
5) System.out.println("Class Loading");
6) }
7) }
8) class Test
9) {
10) public static void main(String[] args) throws Exception
11) {
12) Class c=Class.forName("AAA");
13) }
14) }
If we run this code the JVM will provide the following exception details.
• Exception Name: java.lang.ClassNotFoundException
• Exception Description: AAA
• Exception Location: Test.java: 12
• InstantiationException 5.IllegalArgumentException
When JVM encounter 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 available, if
parameterized constructor 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:
1) class A
2) {
3) static
4) {
5) System.out.println("Class Loading");
6) }
7) A(int i)
8 http://youtube.com/durgasoftware
Core Java
8) {
9) System.out.println("Object Creating");
10) }
11) }
12) class Test
13) {
14) public static void main(String[] args) throws Exception
15) {
16) Class c=Class.forName("A");
17) Object obj=c.newInstance();
18) }
19) }
If run the above code then JVM will provide an exception with the following details.
• Exception Name : java.lang.InstantiationException
• Exception Description: A
• Exception Location:Test.java: 17
EX:
1) class A
2) {
3) static
4) {
5) System.out.println("Class Loading");
6) }
7) private A()
8) {
9) System.out.println("Object Creating");
10) }
11) }
12) class Test
13) {
14) public static void main(String[] args) throws Exception
15) {
16) Class c=Class.forName("A");
17) Object obj=c.newInstance();
18) }
19) }
If we run the above code then JVM will rise an exception with the following details
• Exception Name : java.lang.IllegalAccessException
• Exception Decrition: Test class cannot access the members of class A with the
modifier "private".
• Exception Location" Test.java: 17
9 http://youtube.com/durgasoftware
Core Java
'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:
1) class Test
2) {
3) public static void main(String[] args)throws Exception
4) {
5) String accNo=args[0];
6) String accName=args[1];
7) int pin_Num=Integer.parseInt(args[2]);
8) String accType=args[3];
9) System.out.println("Account Details");
10) System.out.println("---------------------");
11) System.out.println("Account Number :"+accNo);
12) System.out.println("Account Name :"+accName);
13) System.out.println("Account Type :"+accType);
14) System.out.println("Account PIN Number:"+pin_Num);
15) if(pin_Num>=1000 && pin_Num<=9999)
16) {
17) System.out.println("valid PIN Number");
18) }
19) else
20) {
21) throw new RuntimeException("Invalid PIN Number, enter Valid 4 digit PIN
Number");
22) }
23) }
24) }
D:\javaapps>javac Test.java
D:\javaapps>java Test abc123 AAA 1234 Ssavings
--- Account details without 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)
10 http://youtube.com/durgasoftware
Core Java
• '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.
Status:Valid
Status:InValid
Status:Valid
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.
11 http://youtube.com/durgasoftware
Core Java
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:
1) import java.io.*;
2) class A {
3) void add() throws Exception {
4) concat();
5) }
6) void concat() throws IOException {
7) throw new IOException();
8) }
9) }
10) class Test {
11) public static void main(String args[]) throws Throwable {
12) A a = new A();
13) a.add();
14) }
15) }
12 http://youtube.com/durgasoftware
Core Java
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
Exception 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.
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 locations 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.
13 http://youtube.com/durgasoftware
Core Java
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.
• e.printStackTrace()
• System.out.println(e):
• System.out.println(e.getMessage());
• e.printStackTrace():
It will display the exception details like Exception Name, Exception Description and
Exception Location.
• 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.
• System.out.println(e.getMessage()):
Where getMessage() method will return a String contains the exception details like
only Description of the exception.
EX:
1) class Test {
2) public static void main(String args[]) {
3) try {
4) throw new ArithmeticException("My Arithmetic Exception");
5) }
6) catch(ArithmeticException e) {
7) e.printStackTrace();
8) System.out.println();
9) System.out.println(e);
10) System.out.println();
11) System.out.println(e.getMessage());
12) }
13) finally {
14 http://youtube.com/durgasoftware
Core Java
14) }
15) }
16) }
Output:
java.lang.ArithmeticException:My Arithmetic Exception
at Test.main(Test.java:7)
My Arithmetic Exception
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.
15 http://youtube.com/durgasoftware
Core Java
Output:
Before try
Inside try
Inside finally
After finally
EX:
1) class Test {
2) public static void main(String args[]) {
3) System.out.println("Before Try");
4) try {
5) System.out.println("Before Exception in try");
6) float f = 100/0;
7) System.out.println("After Exception in try");
8) }
9) catch(Exception e) {
10) System.out.println("Inside Catch");
11) }
12) finally {
13) System.out.println("Inside Finally");
14) }
15) System.out.println("After Finally");
16) }
17) }
Output:
Before try
Before exception in try
Inside catch
Inside finally
After finally
16 http://youtube.com/durgasoftware
Core Java
Output:
30
NOTE: finally block provided return statement is the finally return statement for the
method
Syntax:
try {
}
finally {
}
17 http://youtube.com/durgasoftware
Core Java
EX:
1) class Test {
2) public static void main(String args[]) {
3) System.out.println("Before try");
4) try {
5) System.out.println("Before Exception inside try");
6) int i = 100;
7) int j-0;
8) float f = i/j;
9) System.out.println("After Exception inside try");
10) }
11) finally {
12) System.out.println("Inside finally");
13) }
14) System.out.println("After Finally");
15) }
16) }
Output:
Before try
Before exception inside try
Inside finally
Exception in thread “main” java.lang.ArithmeticException:/by zero
at Test.main(Test.java:11)
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:
try {
-------
--------
}
catch(Exception e) {
-------------
-------------
}
18 http://youtube.com/durgasoftware
Core Java
Yes, it is possible to provide try-catch-finally inside try block, inside catch block and inside
finally block.
Syntax-1:
try {
try {
}
catch(Exception e) {
}
finally {
}
}
catch(Exception e) {
}
finally {
}
Syntax-2:
try {
}
catch(Exception e) {
try {
}
catch(Exception e)
{
}
finally {
}
}
finally {
}
Syntax-3:
try {
}
catch(Exception e) {
}
finally {
try {
19 http://youtube.com/durgasoftware
Core Java
}
catch(Exception e) {
}
finally {
}
}
Ex 1:
try {
}
catch(ArithmeticException e) {
}
catch(ClassCastException e) {
}
catch(NullPointerException e) {
}
Status:Valid Combination
Ex 2:
try {
}
catch(NullPointerException e) {
}
catch(ArithmeticException e) {
}
catch(ClassCastException e) {
}
status:Valid Combination
20 http://youtube.com/durgasoftware
Core Java
Ex 3:
try {
}
catch(ArithmeticException e) {
}
catch(RuntimeException e) {
}
catch(Exception e) {
}
Status:Valid
Ex 4:
try {
}
catch(Exception e) {
}
catch(RuntimeException e) {
}
catch(ArithmeticException e) {
}
status: Invalid
Ex 5:
try {
throws new ArithmeticException("My Exception");
}
catch(ArithmeticException e) {
}
catch(IOException e) {
}
catch(NullPointerException e) {
}
Status:Invalid
Ex 6:
try {
throw new IOException("My Exception");
}
catch(ArithmeticException e) {
}
catch(IOException e) {
}
21 http://youtube.com/durgasoftware
Core Java
catch(NullPointerException e) {
}
status:Valid
22 http://youtube.com/durgasoftware
Core Java
23 http://youtube.com/durgasoftware
Core Java
59) }
60) finally
61) {
62) System.out.println("**********ThanQ, Visit Again*********");
63) }
64) }
65) }
66) class Test
67) {
68) public static void main(String[] args)
69) {
70) Account acc1=new Account("abc123", "Durga", "Savings", 10000);
71) Transaction tx1=new Transaction();
72) tx1.withdraw(acc1, 5000);
73) System.out.println();
74) Account acc2=new Account("xyz123", "Anil", "Savings", 10000);
75) Transaction tx2=new Transaction();
76) tx2.withdraw(acc2, 15000);
77) }
78) }
If we specify "Exception" class along with catch block then it able to catch and handle all
the exceptions which are either same as Exception or child classes to Exception, this
approach will not handling exceptions individually, it will handle all the exceptions in the
common way.
If we want to handle to the Exceptions separately then we have to use multiple catch
blocks for a single try block.
try {
} catch(ArithmeticException e) {
} catch(NullPointerException e) {
} catch(ClassCastException e) {
24 http://youtube.com/durgasoftware
Core Java
}
If we use this approach then number of catch blocks are increased.
In Java applications, if we want to handle all the exceptions separately and by using a
single catch block then we have to use "JAVA7" provided multi- catch block.
Syntax:
try {
}
catch(Exception1 | Exception2 |....|Exception-n e) {
}
Where Exception1, Exception2....must not have inheritance relation otherwise
Compilation error will be raised.
EX:
1) class Test {
2) public static void main(String args[]) {
3) try {
4) /* int a = 10;
5) int b = 0;
6) float c = a/b;
7) */
8) /*java.util.Date d = null;
9) System.out.println(d.toString());
10) */
11) int[] a = {1, 2, 3, 4, 5};
12) System.out.println(a[10]);
13) }
14) catch(ArithmeticException | NullPointerException |
ArrayIndexOutOfBoundsException e) {
15) e.printStackTrace();
16) }
17) }
If we want to manage the resources along with try-catch-finally in Java applications then
we have to use the following conventions.
25 http://youtube.com/durgasoftware
Core Java
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 number of instructions in Java
applications.
To overcome all the above problems, JAVA 7 version has provided a new Feature in the
form of "Try-With-Resources" or "Auto Closeable Resources".
In the case of "Try-With-Resources", just we have to declare and create the resources
along with "try"[not inside try block, not before try block] and no need to close these
resources inside the finally block, why because, JVM will close all the resources
automatically when flow of execution is coming out from "try" block.
26 http://youtube.com/durgasoftware
Core Java
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:
1) try(File f = new File("abc.txt");
2) BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
3) Connection con = DriverManager.getConnection("jdbc:odbc:nag","system","durga
");)
4) {
5) -------
6) -------
7) }
8) catch(Exception e) {
9) e.printStackTrace();
10) }
NOTE: In Java, all the predefined Stream classes, File class, Connection interface are
extends/implemented "java.io.AutoCloseable" interface predefined.
27 http://youtube.com/durgasoftware