EXCEPTION HANDLING
EXCEPTION HANDLING
EXCEPTION HANDLING
When an application is developed, the application may contain some errors. The
errors that occur in the applications are classified into two types:
1. Compiler time errors
2. Runtime errors
Complier time error: The errors that occur in a program or application because of
the syntactical mistakes are called as compile time errors.
Runtime errors: The errors that occur in a program at execution time, because of
either programmer failure or JVM failure are called as run time errors.
Exception hierarchy:
Object: Object is the super most class of all the classes in Java.
Throwable: Throwable is the super most class of all the runtime errors in Java.
Throwable is the subclass of Object class.
Exception and Error are the subclasses of Throwable.
Exception: An exception is a runtime error, which occurs because of the
programmer failure(logical failure, invalid inputs etc). Exception is the super most
class of all the Exceptions.
Exceptions are classified into two types based on when they are identified:
1. Compile time exception: The exceptions which occur at runtime and which can
be identified before runtime or during compilation time are called as compiler
time exceptions.
2. Runtime exception: The exceptions which occur at runtime and which can be
identified during runtime are called as runtime exceptions.
Error: An Error is a runtime error which occurs because of the JVM failure. Error is
the super most class of all the Error classes.
The exceptions are classified into two types based on whether they are handled or
not:
1. Checked exception: The exceptions whose handling is mandatory are called as
checked exception.
2. Unchecked exception: The exceptions whose handling is optional are called as
unchecked exception.
According to the exception hierarchy, Runtime Exception and its subclasses, Error
and its subclasses are unchecked and the remaining are checked.
If an application contains an exception, then, the application will be terminated
abnormally leading to incomplete execution. In order to execute the code
completely and terminate the application normally then, we need to take the help
of exception handling.
Exception handling is a process of finding an alternate solution so that the
remaining code execute completely and terminates normally.
Note: The exception handling process will not remove the exception from the
program.
The code that performs exception handling will be called as exception handler.
Example:
public class Sample {
public static void main(String[] args) {
System.out.println(“line one”);
System.out.println(10/0);
System.out.println(“line three”);
System.out.println(“line four”);
}
}
When an exception occurs in an application, an object of its corresponding
exception class will be created and then, all the details related to that exception
will be stored into that object and then, the object will be thrown to the JVM by
that method in which an exception has occurred.
The JVM will catch the object and reads the information available in that object and
then the JVM looks for exception handling code, if not available the JVM will call
default exception handler.
The responsibility of the default exception handler is to display the information
available in the exception object and terminate the application abnormally and
therefore leading to incomplete execution.
The keywords related to exception handling concept are:
1. try
2. catch
3. finally
4. throws
5. throw
try: A try is a block, in which we can specify a group of statements, that may
generate an exception.
Syntax:
try {
statements generating exception;
}
A try block can contain any number of statements but recommended to specify
only those statements which may generate the exception.
catch: A catch is a block, in which we can specify a group of statements, that will
display the information of the exception that has occurred.
Syntax:
catch(AnyException ref) {
statements displaying exception information;
}
Note: Every catch block must contain a reference of any one of the exception.
finally: A finally is a block, in which we can specify a group of statements, that will
perform code cleanup activities like releasing memory, resources etc.
Syntax:
finally {
statements performing code cleanup activities,
}
Note: we cannot guarantee the execution of the try and catch block but the
execution of finally block is guarantee.
1) A try block must be followed by either a catch block or a finally block.
2) A catch block must be preceded by either try or catch block but in the hierarchy,
we must specify try block on the top.
3) A catch block can be followed by either a catch block or finally block.
4) A finally block must be preceded by either a try or a catch but in the hierarchy,
we must specify try block on the top.
5) A try block can be followed by any number of catch blocks (zero or more).
6) A try block contains multiple catch blocks and if the exceptions specified in the
catch blocks have IS-A relationship then, they have to specified in the order
from child to parent, but if the exceptions don’t have IS-A relationship then, we
can specify them in any order.
7) A try block can contain almost one finally block.
8) We can specify the statements either before the blocks or after blocks or inside
the blocks but not in between the blocks.
9) A try block may contain multiple catch blocks but, it can execute atmost one
catch block, which in matching.
10) A try block may contain multiple catch blocks but, none of the catch blocks
may execute in the following situation.
i. When there is no exception in the program.
ii. An exception has occurred but not matching.
11) The try, catch and finally blocks can be nested either in try or catch or finally
and they can be nested any number of times.
12) A program can contain any number of combinations of try, catch, and finally
blocks.
13) If statements in a try block generate an exception, then, the control will be
transferred from inside the try block to the corresponding catch block.
14) Once the control is out of the try block it cannot return back to the try block.
Example:
public class Sample {
public static void main (String[] args) {
System.out.println(“line one”);
try {
String s1 = args[0];
String s2 = args[1];
int a = Integer.parseInt(s1);
int b = Integer.parseInt(s2);
System.out.println(a/b);
}
catch(ArithmeticException ae) {
ae.printStackTrace();
}
catch(ArrayIndexOutOfBoundsExecption aioobe) {
aioobe.printStackTrace();
}
finally {
System.out.println(“special line”);
}
System.out.println(“line four”);
}
}
Multi catch block: In java 1.7 version we can handle multiple exceptions by writing
a single catch block.
Syntax:
catch(Exception1 | Exception2 | Exception3… ref) {
statements;
}
Example:
catch(ArithmeticException | ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
The exceptions specified in multi catch block must not have IS-A relationship.
throws: The throws keyword is designed to transfer or delegate the responsibility
of exception handling to its caller.
Syntax:
returntype methodName(parameters) throws Exception1, Exception2, … {
statements;
}
Note: The throws keyword will not handle exceptions.
Example:
public class Sample {
public static void main(String[] args) {
System.out.println(“main first line”);
try {
show();
}
catch(ArithmeticException ae) {
ae.printStackTrace();
}
System.out.println(“main last line”);
}
static void show() throws ArithmeticException {
System.out.println(“show first line”);
System.out.println(6/0);
System.out.println(“show last line”);
}
}
In the above program, an exception has occurred in show() and it is the
responsibility of the show() to handle the exception, but instead of show() handling
the exception, it has transferred the responsibility of exception handling to its
caller(main() method).
Note: Exception handling can be done only by using try-catch block.
throw: The throw keyword is used to throw an exception object explicitly to the
JVM.
Syntax:
throw AnyExceptionObject;
Different ways of displaying the information of the exception:
1) printStackTrace(): This method can be used to display the detailed information
of the exception that has occurred. This method will provide details like
exception name, reason for the occurrence of the exception, line number,
method name, class name, program name.
try {
System.out.println(10/0);
}
catch(ArithmeticException ae) {
ae.printStackTrace();
}
java.lang.ArithmeticException : / by zero at Sample.main(Sample.java:7)
2) toString(): The To String method is used to display only the exception name and
the reason for the occurrence of the exception.
try {
System.out.println(10/0);
}
catch(ArithmeticException ae) {
System.out.println(ae);
//System.out.println(ae.toString());
}
java.lang.ArithmeticException : / by zero
3) getMessage(): The getMessage() can be used to display only the reason for the
occurrence of the exception.
try {
System.out.println(10/0);
catch(ArithmeticException ae) {
System.out.println(ae.getMessage());
}
/ by zero
4) User defined Message: If we don’t want the output to be provided by the
predefined methods then, we can display our own message by using
System.out.println().
try {
System.out.println(10/0);
}
catch(ArithmeticException ae) {
System.out.println(“ArithmeticException has occurred”);
System.out.println(“it is a user defined message”);
}
Arithmetic has occurred
it is a user defined message
Additional Information:
User defined exception: If an exception is created by a user or a programmer then,
it is called as user defined exception.
The user defined exceptions has to be created when none of the predefined
exceptions are matching our application requirement.
Procedure for creating user defined exception:
1. Every predefined exception is a class and therefore the user defined exception
should also be a class.
2. Every predefined exception is a subclass of Exception class either directly or
indirectly therefore every user defined exception should also be a subclass of
Exception class either directly or indirectly.
3. If the application doesn’t know when to generate the exception and which one
to generate the exception and therefore it is the responsibility of the
programmer to explicitly create an object and throw it to the JVM by using
throw keyword.
4. Every user defined exception must have two constructors, one zero
parameterized constructor and the other parameterized constructor taking one
parameter of String type.
Example:
class SmallAgeException extends RuntimeException {
SmallAgeException() {
}
SmallAgeException(String str) {
super(str);
}
}
class BigAgeException extends RuntimeException {
BigAgeException() {
}
BigAgeException(String str) {
super(str);
}
}
public class Sample {
public static void main(String[] args) {
int age = Integer.parseInt(args[0]);
try {
if(age < 20) {
throw new SmallAgeException(“your age is less than 20”);
}
else if(age > 30) {
throw new BigAgeException(“your age is more than 30”);
}
else {
System.out.println(“you are eligible”);
}
}
catch(SmallAgeException sae) {
sae.printstackTrace();
}
catch(BigAgeException bae) {
bae.printStackTrace();
}
System.out.println(“have a good day”);
}
}
IMPORTANT QUESTIONS:
3. Is it possible to define multiple catch blocks in Java? Justify your answer with program.
4. Is it possible to rethrow the exceptions in Java? Justify your answer with program.
6. Explain nested try statements and multiple catch blocks with a suitable program.