Exception Handling
Exception Handling
EXCEPTION
The unwanted, unexpected activities which disturbs the normal flow of the program is
known as exception. In Java, an exception is an event that disrupts the normal flow of
the program.
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.
class ExceptionExample
{
public static void main(String args[]){
sum();
}
public static void sum(){
mul();
}
public static void mul(){
System.out.println("Hello World");
}
}
Note: If I put some exception type code anywhere, exception arise and if the
handling code doesn’t provide by the caller method then JVM destroys the caller
methods and hand over this code to the default Exception handler which does
nothings. It just prints the exception.
class ExceptionExample
{
public static void main(String args[]){
sum();
}
public static void sum(){
mul();
}
public static void mul(){
System.out.println(10/0);
}
1
}
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy. It is
inherited by two subclasses: Exception and Error. The hierarchy of Java Exception
classes is given below:
2
The most important Question of java Exception
What is checked and unchecked Exception?
The exception which is checked at the compile time by the compiler for the smooth
running of the program at run time is known as checked exception.
The exception which is checked at the run time is known as unchecked exception.
Note: All the runtime exception and the errors are by default unchecked exception
and the rest of all are checked exception.
3
Without try catch block
class test
{
public static void main(String args[])
{
System.out.println("Statement 1");
System.out.println(10/0);
System.out.println("Statement 2");
System.out.println("Statement 3");
}
}
With try catch block
class Test1
{
public static void main(String args[])
{
System.out.println("Statement 1");
try
{
System.out.println(10/0);
}
catch(ArithmeticException e)
{
System.out.println(10/2);
}
System.out.println("Statement 2");
System.out.println("Statement 3");
}
}
Hence we should only keep the risky code in the try block
4
Control Flow inside Try catch block
try
{
statement 1;
statement 2;
statement 3;
}
catch(ArithmeticException e)
{
statement 4;
}
statement 5;
1. If there is no exception.
5
public static void main(String args[])
{
divide();
}
}
Output
System.out.println(e.getMessage());
6
Try with multiple catch block
Trytry Try
{ { {
10/0;
10/0; 10/0;
} } }
catch(ArithmeticException
catch(Exception e) e){ catch(ArithmeticException e)
{ } {
} catch(Exception e){ }
}
catch(ArithmeticException e) catch(Exception e)
{ {
} }
try{
int a[]=new int[5];
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
7
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
public class MultipleCatchBlock3 {
8
catch(Exception e){
System.out.println("common task completed");
}
catch(ArithmeticException e){
System.out.println("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("task 2 completed");
}
System.out.println("rest of the code...");
}
}
Common Scenarios of Java Exceptions
1) A scenario where ArithmeticException occurs
If we have a null value in any variable, performing any operation on the variable
throws a NullPointerException.
String s=null;
System.out.println(s.length()); //NullPointerException
String s="abc";
9
When an array exceeds to its size, the ArrayIndexOutOfBoundsException
occurs. there may be other reasons to occur
ArrayIndexOutOfBoundsException.
a[10]=50; //ArrayIndexOutOfBoundsException
1. The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following
tasks:
Prints out exception description.
Prints the stack trace (Hierarchy of methods where the exception
occurred).
10
Causes the program to terminate.
2. But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.
Syntax
try
{
statement 1;
statement 2;
try
{
statement 3;
statement 4;
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
}
}
catch(Exception e1)
{
}
}
catch(Exception e3)
{
}
11
Example
try{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
12
Example 2
public class NestedTryBlock2 {
public static void main(String args[])
{
try {
try {
try {
int arr[] = { 1, 2, 3, 4 };
System.out.println(arr[10]);
}
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println(" inner try block 2");
}
}
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println("inner try block 1");
}
}
catch (ArrayIndexOutOfBoundsException e4) {
System.out.print(e4);
System.out.println(" outer (main) try block");
}
}
}
Java finally block is always executed whether an exception is handled or not. Therefore,
it contains all the necessary statements that need to be printed regardless of the
exception occurs or not.
13
The finally block follows the try-catch block.
Note: If you don't handle the exception, before terminating the program, JVM
executes finally block (if any).
Flowchart
14
}
catch(NullPointerException e){
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Case 2: When an exception occur but not handled by the catch block
Rule: For each try block there can be zero or more catch blocks, but only one finally
block.
15
Note: The finally block will not be executed if the program exits (either by calling
System.exit() or by causing a fatal error that causes the process to abort).
Customize exception means the exception created by the programmer. User defined
exception.
16
class Test10{ Exception object created and hand
public static void main(String args[]{ Over this Exception object to the
JVM Internally
System.out.println(10/0);
class Test10{
class Test10{
System.out.println(10/0);
System.out.println("Hello");
class Test10{
System.out.println("Hello");
In the first class the code will easily compile but for the second class the code does
not compile.
class Test10{
17
static ArithmeticException e= new ArithmeticException();
catch (Exception e) {
System.out.println("Exception caught:Division by zero");
18
System.out.println(e);
}
finally {
System.out.println("I am in final block");
}
}
}
Another Example
class Test11{
public static void main(String args[])
{
throw new Exception(); // CE because of checked Exception
throw new Error(); // CE because of unchecked Exception
}
}
throws Keyword
To delegate the responsibility of the exception handling to the caller we use throws
keyword.
public static void main(String args[]){ public static void main(String args[]) throws Exception
Thread.sleep(1000); {
} Thread.sleep(1000);
Which approach is recommended and which one is not recommended?
} }
19
}
If really a checked exception occurs and when we use throws keyword to handle the
exception, throws keyword delegate it to JVM and JVM is responsible to handle the
exception.
If JVM handles the exception, it means program terminates abnormally. So, throws
keyword is not at all recommended over try catch block.
1 2
try try
{ {
System.out.println("Hello"); System.out.println("Hello");
} }
catch(ArithmeticException e) catch(Exception e)
{ {
} }
3 4
try try
{ {
20 System.out.println("Hello");
System.out.println("Hello");
} }
catch(InterruptedException e) catch(IOException e)
{
5
try
{
System.out.println("Hello");
}
catch(Error e)
{
}
But the remaining 3 and 4 gives compile time Error. (fully checked)
Rule: within the try block if there is no chance of rising any exception you can’t
write the catch block but this rule is applicable only for fully checked exception.
21
Difference between Final, finally, Finalize.
final
final is keyword which is used only for
1. class
2. method
3. variable
If we declare a class as a final, we can’t extend the class it means inheritance is not
possible.
If we declare a method as a final, we can’t override the method in the child class it
means overridden in not possible
If we declare a variable as a final, we can’t change the value of that variable it means the
variable becomes constant.
finally
22
finally, is a block associated with try catch. The main purpose of finally block is to
maintain cleanup code. The specialty of the finally block is, it will always execute
weather the exception occurs or not.
try
{
//Risky code
}
catch ()
{
//Handling code
}
finally
{
//Clean up code, resources deallocation code.
}
finalize()
finalize() is a method associated with the garbage collector concept. If any object
doesnot refer by any reference variable it means that object is eligible for garbage
collector.
1. Before destroying the object, garbage collector calls finalize() method to cleanup
the activities associated with that object.
2. Once the cleanup activities are completed, immediately the garbage collector
destroy the object.
Just before destroying the object, garbage collector calls the finalize() method for
cleanup activities.
Garbage
collector
object
finalize()
23
Database
Network
finally block and finalize() method both are used to clean up the code
then where is the difference.
finally block meant for try block open resources clean up activities.
finalize() method meant for object related clean up code.
24