Java Exception Handling
Exception Handling is a mechanism to handle exception at runtime. Exception is a condition
that occurs during program execution and lead to program termination abnormally. There can
be several reasons that can lead to exceptions, including programmer error, hardware failures,
files that need to be opened cannot be found, resource exhaustion etc.
Suppose we run a program to read data from a file and if the file is not available then the
program will stop execution and terminate the program by reporting the exception message.
The problem with the exception is, it terminates the program and skip rest of the execution
that means if a program have 100 lines of code and at line 10 an exception occur then
program will terminate immediately by skipping execution of rest 90 lines of code.
To handle this problem, we use exception handling that avoid program termination and
continue the execution by skipping exception code.
Java exception handling provides a meaningful message to the user about the issue rather
than a system generated message, which may not be understandable to a user.
Uncaught Exceptions
Lets understand exception with an example. When we don't handle the exceptions, it leads to
unexpected program termination. In this program, an ArithmeticException will be throw due
to divide by zero.
class UncaughtException
public static void main(String args[])
int a = 0;
int b = 7/a; // Divide by zero, will lead to exception
This will lead to an exception at runtime, hence the Java run-time system will construct an
exception and then throw it. As we don't have any mechanism for handling exception in the
above program, hence the default handler (JVM) will handle the exception and will print the
details of the exception on the terminal.
1
Java Exception
A Java Exception is an object that describes the exception that occurs in a program. When an
exceptional events occurs in java, an exception is said to be thrown. The code that's
responsible for doing something about the exception is called an exception handler
How to Handle Exception
Java provides controls to handle exception in the program. These controls are listed below.
Try : It is used to enclose the suspected code.
Catch: It acts as exception handler.
Finally: It is used to execute necessary code.
Throw: It throws the exception explicitly.
Throws: It informs for the possible exception.
We will discuss about all these in our next tutorials.
Types of Exceptions
In Java, exceptions broadly can be categories into checked exception, unchecked exception
and error based on the nature of exception.
Checked Exception
The exception that can be predicted by the JVM at the compile time for example :
File that need to be opened is not found, SQLException etc. These type of exceptions
must be checked at compile time.
2
Unchecked Exception
Unchecked exceptions are the class that extends RuntimeException class. Unchecked
exception are ignored at compile time and checked at runtime. For example :
ArithmeticException, NullPointerException, Array Index out of Bound exception.
Unchecked exceptions are checked at runtime.
Error
Errors are typically ignored in code because you can rarely do anything about an
error. For example, if stack overflow occurs, an error will arise. This type of error
cannot be handled in the code.
Java Exception class Hierarchy
All exception types are subclasses of class Throwable, which is at the top of exception class
hierarchy.
Exception class is for exceptional conditions that program should catch. This class is
extended to create user specific exception classes.
RuntimeException is a subclass of Exception. Exceptions under this class are
automatically defined for programs.
3
Exceptions of type Error are used by the Java run-time system to indicate errors
having to do with the run-time environment, itself. Stack overflow is an example of
such an error.
try and catch in Java
Try and catch both are Java keywords and used for exception handling. The try block is
used to enclose the suspected code. Suspected code is a code that may raise an exception
during program execution.
For example, if a code raise arithmetic exception due to divide by zero then we can wrap that
code into the try block.
try{
int a = 10;
int b = 0
int c = a/b; // exception
The catch block also known as handler is used to handle the exception. It handles the
exception thrown by the code enclosed into the try block. Try block must provide a catch
handler or a finally block. We will discuss about finally block in our next tutorials.
The catch block must be used after the try block only. We can also use multiple catch block
with a single try block.
try{
int a = 10;
int b = 0
int c = a/b; // exception
}catch(ArithmeticException e){
[Link](e);
4
Try Catch Syntax
To declare try catch block, a general syntax is given below.
try{
// suspected code
}catch(ExceptionClass ec){}
Exception handling is done by transferring the execution of a program to an appropriate
exception handler (catch block) when exception occurs.
Example: Handling Exception
Now lets understand the try and catch by a simple example in which we are dividing a
number by zero. The code is enclosed into try block and a catch handler is provided to handle
the exception.
class Excp
public static void main(String args[])
int a,b,c;
try
a = 0;
b = 10;
c = b/a;
[Link]("This line will not be executed");
catch(ArithmeticException e)
[Link]("Divided by zero");
[Link]("After exception is handled");
5
}
Divided by zero
After exception is handled
Explanation
An exception will thrown by this program as we are trying to divide a number by zero
inside try block. The program control is transferred outside try block. Thus the line "This
line will not be executed" is never parsed by the compiler. The exception thrown is handled
in catch block. Once the exception is handled, the program control is continue with the next
line in the program i.e after catch block. Thus the line "After exception is handled" is printed.
Multiple catch blocks
A try block can be followed by multiple catch blocks. It means we can have any number of
catch blocks after a single try block. If an exception occurs in the guarded code(try block) the
exception is passed to the first catch block in the list. If the exception type matches with the
first catch block it gets caught, if not the exception is passed down to the next catch block.
This continue until the exception is caught or falls through all catches.
Multiple Catch Syntax
To declare the multiple catch handler, we can use the following syntax.
try
// suspected code
catch(Exception1 e)
// handler code
catch(Exception2 e)
// handler code
6
Now lets see an example to implement the multiple catch block that are used to catch possible
exception.
The multiple catch blocks are useful when we are not sure about the type of exception during
program execution.
Examples for Multiple Catch blocks
In this example, we are trying to fetch integer value of an Integer object. But due to bad
input, it throws number format exception.
class Demo{
public static void main(String[] args) {
try
Integer in = new Integer("abc");
[Link]();
catch (ArithmeticException e)
[Link]("Arithmetic " + e);
catch (NumberFormatException e)
[Link]("Number Format Exception " + e);
Number Format Exception [Link]: For input string: "abc"
In the above example, we used multiple catch blocks and based on the type of exception
second catch block is executed.
7
Example: Multiple Exception
Lets understand the use of multiple catch handler by one more example, here we are using
three catch handlers in catch the exception.
public class CatchDemo2
public static void main(String[] args)
try
int a[]=new int[10];
[Link](a[20]);
catch(ArithmeticException e)
[Link]("Arithmetic Exception --> "+e);
catch(ArrayIndexOutOfBoundsException e)
[Link]("ArrayIndexOutOfBounds Exception --> "+e);
catch(Exception e)
[Link](e);
8
At a time, only one exception is processed and only one respective catch block is executed.
Example for Unreachable Catch block
While using multiple catch statements, it is important to remember that sub classes of class
Exception inside catch must come before any of their super classes otherwise it will lead to
compile time error. This is because in Java, if any code is unreachable, then it gives compile
time error.
class Excep
public static void main(String[] args)
try
int arr[]={1,2};
arr[2]=3/0;
catch(Exception e) //This block handles all Exception
[Link]("Generic exception");
catch(ArrayIndexOutOfBoundsException e) //This block is unreachable
[Link]("array index out of bound exception");
9
Generic exception
Nested try statement
try statement can be nested inside another block of try. Nested try block is used when a part
of a block may cause one error while entire block may cause another error. In case if
inner try block does not have a catch handler for a particular exception then the outer try
catch block is checked for match.
class Excep
public static void main(String[] args)
try
int arr[]={5,0,1,2};
try
int x = arr[3]/arr[1];
catch(ArithmeticException ae)
[Link]("divide by zero");
arr[4]=3;
catch(ArrayIndexOutOfBoundsException e)
[Link]("array index out of bound exception");
10
divide by zero
array index out of bound exception
Important points to Remember
1. If you do not explicitly use the try catch blocks in your program, java will provide a
default exception handler, which will print the exception details on the terminal,
whenever exception occurs.
2. Super class Throwable overrides toString() function, to display error message in
form of string.
3. While using multiple catch block, always make sure that sub-classes of Exception
class comes before any of their super classes. Else you will get compile time error.
4. In nested try catch, the inner try block uses its own catch block as well as catch block
of the outer try, if required.
5. Only the object of Throwable class or its subclasses can be thrown.
Java throw, throws and finally Keyword
Throw, throws and finally are the keywords in Java that are used in exception
handling. The throw keyword is used to throw an exception and throws is used to declare the
list of possible exceptions with the method signature. Whereas finally block is used to
execute essential code, specially to release the occupied resources.
Now lets discuss each in details with the examples.
Java Throw
The throw keyword is used to throw an exception explicitly. Only object of Throwable class
or its sub classes can be thrown. Program execution stops on encountering throw statement,
and the closest catch statement is checked for matching type of exception.
Syntax :
throw ThrowableInstance
Creating Instance of Throwable class
We allows to use new operator to create an instance of class Throwable,
new NullPointerException("test");
This constructs an instance of NullPointerException with name test.
11
Example throw Exception
In this example, we are throwing Arithmetic exception explicitly by using the throw keyword
that will be handle by catch block.
class Test
static void avg()
try
throw new ArithmeticException("demo");
catch(ArithmeticException e)
[Link]("Exception caught");
public static void main(String args[])
avg();
In the above example the avg() method throw an instance of ArithmeticException, which is
successfully handled using the catch statement and thus, the program prints the output
"Exception caught".
Java throws Keyword
The throws keyword is used to declare the list of exception that a method may throw during
execution of program. Any method that is capable of causing exceptions must list all the
exceptions possible during its execution, so that anyone calling that method gets a prior
knowledge about which exceptions are to be handled. A method can do so by using
the throws keyword.
Syntax:
type method_name(parameter_list) throws exception_list
12
{
// definition of method
Example throws Keyword
Here, we have a method that can throw Arithmetic exception so we mentioned that with the
method declaration and catch that using the catch handler in the main method.
class Test
static void check() throws ArithmeticException
[Link]("Inside check function");
throw new ArithmeticException("demo");
public static void main(String args[])
try
check();
catch(ArithmeticException e)
[Link]("caught" + e);
Inside check function
[Link]: demo
13
Difference between throw and throws
throw throws
throw keyword is used to throw an exception throws keyword is used to declare an exception
explicitly. possible during its execution.
throw keyword is followed by an instance of throws keyword is followed by one or more
Throwable class or one of its sub-classes. Exception class names separated by commas.
throw keyword is declared inside a method throws keyword is used with method signature
body. (method declaration).
We cannot throw multiple exceptions using We can declare multiple exceptions (separated
throw keyword. by commas) using throws keyword.
finally clause
A finally keyword is used to create a block of code that follows a try block. A finally block of
code is always executed whether an exception has occurred or not. Using a finally block, it
lets you run any cleanup type statements that you want to execute, no matter what happens in
the protected code. A finally block appears at the end of catch block.
14
Example finally Block
In this example, we are using finally block along with try block. This program throws an
exception and due to exception, program terminates its execution but see code written inside
the finally block executed. It is because of nature of finally block that guarantees to execute
the code.
Class ExceptionTest
public static void main(String[] args)
int a[] = new int[2];
[Link]("out of try");
try
[Link]("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
15
finally
[Link]("finally is always executed.");
Out of try
finally is always executed.
Exception in thread main java. Lang. exception array Index out of bound exception.
You can see in above example even if exception is thrown by the program, which is not
handled by catch block, still finally block will get executed.
Example : Finally Block
finally block executes in all the scenario whether exception is caught or not. In previous
example, we use finally where exception was not caught but here exception is caught and
finally is used with handler.
class Demo
public static void main(String[] args)
int a[] = new int[2];
try
[Link]("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
catch(ArrayIndexOutOfBoundsException e) {
[Link]("Exception caught");
finally
[Link]("finally is always executed.");
16
}
Exception caught
finally is always executed.
User defined Exception subclass in Java
Java provides rich set of built-in exception classes like: ArithmeticException, IOException,
NullPointerException etc. all are available in the [Link] package and used in exception
handling. These exceptions are already set to trigger on pre-defined conditions such as when
you divide a number by zero it triggers ArithmeticException.
Apart from these classes, Java allows us to create our own exception class to provide own
exception implementation. These type of exceptions are called user-defined exceptions
or custom exceptions.
You can create your own exception simply by extending java Exception class. You can
define a constructor for your Exception (not compulsory) and you can override
the toString() function to display your customized message on catch. Lets see an
example.
Example: Custom Exception
In this example, we are creating an exception class MyException that extends the Java
Exception class and
class MyException extends Exception
private int ex;
MyException(int a)
ex = a;
public String toString()
return "MyException[" + ex +"] is less than zero";
17
}
class Demo
static void sum(int a,int b) throws MyException
if(a<0)
throw new MyException(a); //calling constructor of user-defined
exception class
else
[Link](a+b);
public static void main(String[] args)
try
sum(-10, 10);
catch(MyException me)
[Link](me); //it calls the toString() method of user-
defined Exception
MyException[-10] is less than zero
18
Example: Custom Exception
Lets take one more example to understand the custom exception. Here we created a class
ItemNotFound that extends the Exception class and helps to generate our own exception
implementation.
class ItemNotFound extends Exception
public ItemNotFound(String s) {
super(s);
class Demo
static void find(int arr[], int item) throws ItemNotFound
boolean flag = false;
for (int i = 0; i < [Link]; i++) {
if(item == arr[i])
flag = true;
if(!flag)
throw new ItemNotFound("Item Not Found"); //calling constructor of
user-defined exception class
else
[Link]("Item Found");
19
public static void main(String[] args)
try
find(new int[]{12,25,45}, 10);
catch(ItemNotFound i)
[Link](i);
ItemNotFound: Item Not Found
Points to Remember
1. Extend the Exception class to create your own exception class.
2. You don't have to implement anything inside it, no methods are required.
3. You can have a Constructor if you want.
4. You can override the toString() function, to display customized message.
Chained Exception in Java
Chained Exception was added to Java in JDK 1.4. This feature allows you to relate one
exception with another exception, i.e one exception describes cause of another exception. For
example, consider a situation in which a method throws an ArithmeticException because of
an attempt to divide by zero but the actual cause of exception was an I/O error which caused
the divisor to be zero. The method will throw only ArithmeticException to the caller. So the
caller would not come to know about the actual cause of exception. Chained Exception is
used in such type of situations.
Two new constructors and two new methods were added to Throwable class to support
chained exception.
1. Throwable(Throwable cause)
20
2. Throwable(String str, Throwable cause)
In the first constructor, the paramter cause specifies the actual cause of exception. In the
second form, it allows us to add an exception description in string form with the actual cause
of exception.
getCause() and initCause() are the two methods added to Throwable class.
getCause() method returns the actual cause associated with current exception.
initCause() set an underlying cause(exception) with invoking exception.
Time for an Example!
Lets understand the chain exception with the help of an example, here, ArithmeticException
was thrown by the program but the real cause of exception was IOException. We set the
cause of exception using initCause() method.
import [Link];
public class ChainedException
public static void divide(int a, int b)
if(b == 0)
ArithmeticException ae = new ArithmeticException("top layer");
[Link](new IOException("cause"));
throw ae;
else
[Link](a/b);
public static void main(String[] args)
21
try
divide(5, 0);
catch(ArithmeticException ae) {
[Link]( "caught : " +ae);
[Link]("actual cause: "+[Link]());
caught:[Link]: top layer
actual cause: [Link]: cause
Example
lets see one more example to understand chain exception, here NumberFormatException was
thrown but the actual cause of exception was a null pointer exception.
public class ChainedDemo1
public static void main(String[] args)
try
NumberFormatException a = new NumberFormatException("====>
Exception");
[Link](new NullPointerException("====> Actual cause of the
exception"));
throw a;
22
catch(NumberFormatException a)
[Link](a);
[Link]([Link]());
23