Exception Handling in Java
Exception:
An Exception is an event, which occurs during the execution of a program, that
disrupts the normal flow of the program's Instructions.
Exception Handling:-
The process of converting system error messages into user friendly error message
is known as Exception handling. This is one of the powerful features of Java to handle
run time error and maintain normal flow of java application.
Usage of Exception Handling
Handling the exception is nothing but converting system error generated
message into user friendly error message. Whenever an exception occurs in the java
application, JVM will create an object of appropriate exception of sub class and
generates system error message, these system generated messages are not
understandable by user so need to convert it into user friendly error message. You can
convert system error message into user friendly error message by using exception
handling feature of java.
For Example: when you divide any number by zero then system generate / by
zero so this is not understandable by user so you can convert this message into user
friendly error message like Don't enter zero for denominator.
Hierarchy of Exception classes:
Developed by: Sreedhar.A, CSE Dept, RGUKT Page 1
Following is the list of Java UnChecked Exceptions Defined in [Link].
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
Illegal monitor operation, such as waiting on an unlocked
IllegalMonitorStateException thread.
IllegalStateException Environment or application is in incorrect state.
Requested operation not compatible with the current
IllegalThreadStateException thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was encountered.
Following is the list of Java Checked Exceptions Defined in [Link].
ClassNotFoundException Class not found.
Attempt to clone an object that does not implement the
CloneNotSupportedException Cloneable interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
Type of Exception
Checked Exception
Un-Checked Exception
Checked Exception
Checked Exception are the exception which checked at compile-time. These
exception are directly sub-class of [Link] class.
Checked means checked by compiler so checked exception are checked at
compile-time.
Developed by: Sreedhar.A, CSE Dept, RGUKT Page 2
Un-Checked Exception
Un-Checked Exception are the exception both identifies or raised at run time.
These exception are directly sub-class of [Link] class.
Note: In real time application mostly we can handle un-checked exception.
Only for remember: Un-checked means not checked by compiler so un-checked
exception are checked at run-time not compile time.
Handling the Exception
Handling the exception is nothing but converting system error generated
message into user friendly error message in others word whenever an exception occurs
in the java application, JVM will create an object of appropriate exception of sub class
and generates system error message, these system generated messages are not
understandable by user so need to convert it into user-friendly error message. You can
convert system error message into user-friendly error message by using exception
handling feature of java.
Use Five keywords for Handling the Exception
try
catch
finally
throws
throw
Developed by: Sreedhar.A, CSE Dept, RGUKT Page 3
Syntax for handling the exception
try
{
// statements causes problem at run time
}
catch(type of exception-1 object-1)
{
// statements provides user friendly error message
}
catch(type of exception-2 object-2)
{
// statements provides user friendly error message
}
finally
{
// statements which will execute compulsory
}
Example without Exception Handling
class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, ans=0;
ans=a/0;
[Link]("Denominator not be zero");
}
}
Example of Exception Handling
class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, ans=0;
try
{
ans=a/0;
}
catch (Exception e)
{
Developed by: Sreedhar.A, CSE Dept, RGUKT Page 4
[Link]("Denominator not be zero");
}
}
}
Output
Denominator not be zero
try and catch block:
try block
Inside try block we write the block of statements which causes executions at run
time in other words try block always contains problematic statements.
If any exception occurs in try block then CPU controls comes out to the try block
and executes appropriate catch block.
After executing appropriate catch block, even through we use run time
statement, CPU control never goes to try block to execute the rest of the
statements.
Each and every try block must be immediately followed by catch block that is no
intermediate statements are allowed between try and catch block.
catch block
Inside catch block we write the block of statements which will generates user
friendly error messages.
Catch block will execute exception occurs in try block.
You can write multiple catch blocks for generating multiple user friendly error
messages to make your application strong. You can see below example.
At a time only one catch block will execute out of multiple catch blocks.
in catch block you declare an object of sub class and it will be internally
referenced by JVM.
Syntax
try
{
.....
}
/* Here no other statements are allowed
between try and catch block */
catch()
{
....
}
Developed by: Sreedhar.A, CSE Dept, RGUKT Page 5
Each and every try block must contains at least one catch block
One try block can contains another try block that is nested or inner try block can
be possible.
Syntax
try
{
.......
try
{
.......
}
}
Example without Exception Handling
class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, ans=0;
ans=a/0;
[Link]("Denominator not be zero");
}
}
Example of Exception Handling
class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, ans=0;
try
{
ans=a/0;
}
catch (Exception e)
{
[Link]("Denominator not be zero");
}
}
}
Developed by: Sreedhar.A, CSE Dept, RGUKT Page 6
Output:
Denominator not be zero
Multiple catch block
You can write multiple catch blocks for generating multiple user friendly error
messages to make your application strong.
Example
import [Link].*;
class ExceptionDemo
{
public static void main(String[] args)
{
int a, b, ans=0;
Scanner s=new Scanner([Link]);
[Link]("Enter any two numbers: ");
try
{
a=[Link]();
b=[Link]();
ans=a/b;
[Link]("Result: "+ans);
}
catch(ArithmeticException ae)
{
[Link]("Denominator not be zero");
}
catch(Exception e)
{
[Link]("Enter valid number");
}
}
}
Output
Enter any two number: 5 0
Denominator not be zero
Developed by: Sreedhar.A, CSE Dept, RGUKT Page 7
finally Block in Exception Handling
Inside finally block we write the block of statements which will released or close
or terminate the resource (file or database) where data store permanently.
Finally block will execute compulsory
Writing finally block is optional.
You can write finally block for the entire java program
In some of the circumstances one can also write try and catch block in finally
block.
Example
class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, ans=0;
try
{
ans=a/0;
}
catch (Exception e)
{
[Link]("Denominator not be zero");
}
finally
{
[Link]("I am from finally block");
}
}
}
Output
Denominator not be zero
I am from finally block
Throw
throw keyword is used to throw our own exception in the program.
Syntex :
throw new Exception_class
In the below example, class checkDistance has one constructor to check
whether entered distance valid or not. If the distance is less than zero than program
throws a arithmetic exception with message 'Please enter valid distance...' .
Developed by: Sreedhar.A, CSE Dept, RGUKT Page 8
class checkDistance{
int dist;
checkDistance(int dist){
[Link] = dist;
if(dist<0){
throw newArithmeticException("Please enter valid
distance...");
}
else{
[Link]("This is valid distance.");
}
}
public static void main(String args[]){
checkDistance v = newcheckDistance(-10);
}
}
Output :
Exception in thread main [Link]: Please enter valid distance...
Throws
throws is to declare an exception within a method. e.g suppose some
programmer defines a method and he knows that it may causes exception, but he/she
don't want to handle that exception, then this method defined with the throws
keyword.
But when we call this function, it should be call with try and catch block to maintain
the normal flow of the program.
In the below example, a method calc()may causes exeption so we declare this method
with throws keyword. But when we call this method, it should be call whithin try block
to handle the exception.
class throwsDemo {
void calc() throwsArithmeticException {
int c = 100/0;
}
class Demo {
public static void main(String args[]) {
throwsDemo t = new throwsDemo();
try {
[Link]();
Developed by: Sreedhar.A, CSE Dept, RGUKT Page 9
}
catch(Exception e) {
[Link](" Exception handled.... ")
}
}
}
Output :
Exception handled....
Custom Exception in Java
If any exception is design by the user known as user defined or Custom
Exception. Custom Exception is created by user.
Rules to design user defined Exception:
1. Create a package with valid user defined name.
2. Create any user defined class.
3. Make that user defined class as derived class of Exception or RuntimeException
class.
4. Declare parametrized constructor with string variable.
5. call super class constructor by passing string variable within the derived class
constructor.
6. Save the program with public class [Link]
Example:
import [Link].*;
class MyException extends Exception{
MyException(String b) {
super(b);
}
Developed by: Sreedhar.A, CSE Dept, RGUKT Page 10
public class JavaException{
public static void main(String args[]){
try{
throw new MyException("custom Exception");
// throw is used to create a new exception and throw it.
}
catch(MyException e){
[Link](e) ;
}
}
}
}
O/p:
[Link]: custom Exception
Developed by: Sreedhar.A, CSE Dept, RGUKT Page 11