4 - Exception Handling in Java
4 - Exception Handling in Java
An exception (or exceptional event) is a problem that arises during the execution (Runtime) of
a program. When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
Some of these exceptions are caused by user error, others by programmer error, and others
by physical resources that have failed in some manner.
Based on these, we have three categories of Exceptions. You need to understand them to
know how exception handling works in Java.
1) Checked Exception
2) Unchecked Exception
3) Error
1) Java defines several exception classes inside the standard package java.lang.
2) The most general of these exceptions are subclasses of the standard type
RuntimeException. Since java.lang is implicitly imported into all Java programs, most
exceptions derived from RuntimeException are automatically available.
3) Java defines several other types of exceptions that relate to its various class libraries.
Following is the list of Java Unchecked RuntimeException.
Sr.No. Exception & Description
list of Java Checked Exceptions Defined in java.lang. ArithmeticException
1
Sr.No. Exception & Description Arithmetic error, such as divide-by-zero.
ClassNotFoundException ArrayIndexOutOfBoundsException
1 2
Class not found. Array index is out-of-bounds.
CloneNotSupportedException ArrayStoreException
3
2 Attempt to clone an object that does not Assignment to an array element of an incompatible type.
implement the Cloneable interface. ClassCastException
4
IllegalAccessException Invalid cast.
3 IllegalArgumentException
Access to a class is denied. 5
InstantiationException Illegal argument used to invoke a method.
4 Attempt to create an object of an abstract class or IllegalMonitorStateException
interface. 6
Illegal monitor operation, such as waiting on an unlocked thread.
InterruptedException
5 One thread has been interrupted by another IllegalStateException
7
thread. Environment or application is in incorrect state.
NoSuchFieldException IllegalThreadStateException
6 8
A requested field does not exist. Requested operation not compatible with the current thread state.
NoSuchMethodException
7 IndexOutOfBoundsException
A requested method does not exist. 9
Some type of index is out-of-bounds.
NegativeArraySizeException
10
Array created with a negative size.
NullPointerException
11
Invalid use of a null reference.
NumberFormatException
12
Invalid conversion of a string to a numeric format.
SecurityException
13
Attempt to violate security.
StringIndexOutOfBounds
14
Attempt to index outside the bounds of a string.
UnsupportedOperationException
15
An unsupported operation was encountered.
Java Exception Handling Keywords
1. try
2. catch
3. finally
4. throw
5. throws
Java catch block is used to handle the Exception. It must be used after the try block
only.
If the type of exception that occurred is listed in a catch block, the exception is passed
to the catch block. Much as an argument is passed into a method parameter and catch
block executed.
You can use multiple catch block with a single try.
Note2: All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException
must come before catch for Exception.
3) JAVA FINALLY BLOCK
o/p
4) Java throw keyword
Rule1: By default Unchecked Exceptions are Rule2: By default, Checked Exceptions are not
forwarded in calling chain (propagated). forwarded in calling chain (propagated).
5) JAVA THROWS KEYWORD
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
There are two cases:
1. Case1: You caught the exception i.e. handle the exception using try/catch.
2. Case2: You declare the exception i.e. specifying throws with the method.
1) In case you declare the exception, if exception does not occur, the code will be
executed fine.
2) In case you declare the exception if exception occurs, an exception will be
thrown at runtime because throws does not handle the exception.
It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
It is automatically done by the garbage collector (a part of JVM) so we don't need to
make extra efforts.
finalize() method:
1) The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing.
2) This method is defined in Object class{java.lang.Object.finalize()} as :
Note: The Garbage collector of JVM collects only those objects that are created by new
keyword. So if you have created any object without new, you can use finalize method
to perform cleanup processing (destroying remaining objects)
gc() method
If the superclass method does not declare an exception, subclass overridden method cannot
declare the checked exception but it can declare unchecked exception.
1) Rule: If the superclass method does not 2) Rule: If the superclass method does not
declare an exception, subclass overridden declare an exception, subclass overridden
method cannot declare the checked exception. method cannot declare the checked exception
but can declare unchecked exception.
If the superclass method declares an exception, subclass overridden method can declare
same, subclass exception or no exception but cannot declare parent exception.
Example in case subclass overridden method
Example in case subclass overridden method
declares same exception
declares parent exception