Professional Documents
Culture Documents
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.
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
1. Built-in Exceptions
o Checked Exception
o Unchecked Exception
2. User-Defined Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are known as
checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at
compile-time.
The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
These exceptions are checked at compile time. These exceptions are just opposite to the checked
1. These exceptions are handled at compile time exceptions. These exceptions are not checked and
too. handled at compile time.
The code gives a compilation error in the case The code compiles without any error because the
when a method throws a checked exception. exceptions escape the notice of the compiler.
3.
The compiler is not able to handle the These exceptions are the results of user-created
exception on its own. errors in programming logic.
These exceptions mostly occur when the These exceptions occur mostly due to
4.
probability of failure is too high. programming mistakes.
It is required to provide the try-catch and try- In the case of unchecked exception it is not
7.
finally block to handle the checked exception. mandatory.
1
ArithmeticException
Arithmetic error, such as divide-by-zero.
2
ArrayIndexOutOfBoundsException
Array index is out-of-bounds.
3
ArrayStoreException
Assignment to an array element of an incompatible type.
4
ClassCastException
Invalid cast.
5
IllegalArgumentException
Illegal argument used to invoke a method.
6
IllegalMonitorStateException
Illegal monitor operation, such as waiting on an unlocked thread.
7
IllegalStateException
Environment or application is in incorrect state.
8
IllegalThreadStateException
Requested operation not compatible with the current thread state.
9
IndexOutOfBoundsException
Some type of index is out-of-bounds.
10
NegativeArraySizeException
11
NullPointerException
Invalid use of a null reference.
12
NumberFormatException
Invalid conversion of a string to a numeric format.
13
SecurityException
Attempt to violate security.
14
StringIndexOutOfBounds
Attempt to index outside the bounds of a string.
15
UnsupportedOperationException
An unsupported operation was encountered.
1
ClassNotFoundException
Class not found.
2
CloneNotSupportedException
Attempt to clone an object that does not implement the Cloneable interface.
3
IllegalAccessException
Access to a class is denied.
5
InterruptedException
One thread has been interrupted by another thread.
6
NoSuchFieldException
A requested field does not exist.
7
NoSuchMethodException
A requested method does not exist.
Java provides five keywords that are used to handle the exception. The following table describes each.
Keyword Description
The "finally" block is used to execute the necessary code of the program. It
finally
is executed whether an exception is handled or not.
Exceptions Methods
Following is the list of important methods available in the Throwable class.
2
public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3
public String toString()
Returns the name of the class concatenated with the result of getMessage().
4
public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output stream.
5
public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0
represents the top of the call stack, and the last element in the array represents the
method at the bottom of the call stack.
6
public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any
previous information in the stack trace.
There are given some scenarios where unchecked exceptions may occur. They are as follows:
1. int a=50/0;//ArithmeticException
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
If the formatting of any variable or number is mismatched, it may result into NumberFormatException.
Suppose we have a string variable that has characters; converting this variable into digit will cause
NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other
reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.
try...catch block
finally block
throw and throws keyword
The try-catch block is used to handle exceptions in Java. Here's the syntax
of try...catch block:
try {
// code
}
catch(Exception e) {
// code
}
Here, we have placed the code that might generate an exception inside the try block. Every try block is
followed by a catch block.
class Main {
public static void main(String[] args) {
try {
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
Output
In Java, the finally block is always executed no matter whether there is an exception
or not.
The finally block is optional. And, for each try block, there can be only
try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
If an exception occurs, the finally block is executed after the try...catch block.
Otherwise, it is executed after the try block. For each try block, there can be only
class Main {
public static void main(String[] args) {
try {
// code that generates exception
int divideByZero = 5 / 0;
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
finally {
System.out.println("This is the finally block");
}
}
}
Output
In the previous page example, we are dividing a number by 0 inside the try block. Here, this
The exception is caught by the catch block. And, then the finally block is executed.
Note: It is a good practice to use the finally block. It is because it can include important
When we throw an exception, the flow of the program moves from the try block to
class Main {
public static void divideByZero() {
// throw an exception
throw new ArithmeticException("Trying to divide by 0");
Output
class Main {
// declareing the type of exception
public static void findFile() throws IOException {
Output
Output:
Output:
If callee can throw multiple exceptions, then all will be thrown simultaneously.
try {
arr[10] = 11;
}
}
}
class Main {
public static void main(String[] args) {
ListOfNumbers list = new ListOfNumbers();
list.writeList();
}
}
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
class Main {
public static void main (String[] args) {
try{
try{
int[] a={1,2,3};
System.out.println(a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Out of bounds");
}
System.out.println(4/0);
}
catch(ArithmeticException e)
Output:
Out of bounds
ArithmeticException: Divide by 0
Final is used to apply Finally is used in coding, it will be Finalize is used to perform clean-
restrictions on class, method, executed whether an exception is up processing before garbage is
and variable handled or not. collected.