UNIT 3
EXCEPTION HANDLING
Introduction:
Errors are wrongs that can make a program go wrong. An error may produce incorrect output or may
terminate the execution of the program abruptly or even may cause the system to crash. It is therefore
important to detect and manage properly all the error conditions in the program so that the program will
not terminate or crash during execution.
Types of Errors:
Errors may broadly be classified into two categories:
Compile-time errors
Run-time errors
Compile-time errors:
All syntax errors will be detected and displayed by the Java compiler and therefore theses errors are
known as compile-time errors.
Most of the compile-time errors are due to typing mistakes. Typographical errors are hard to find. We
have to check the code word by word, or even character by character. The most common problems are:
Missing semicolons
Missing (or mismatch of) brackets in classes and methods
Misspelling of identifiers and keywords
Missing double quotes in strings
Use of undeclared variables
Incompatible types in assignments/initialization
Bad references to objects
Use of = in place of = = operator
And so on
Run-time errors:
Sometimes program may compile successfully creating the .class file but may not run properly. Such
programs may produce wrong results due to wrong logic or may terminate due to errors such as stack
overflow. Most common run-time errors are:
Dividing an integer by zero
Accessing an element that is out of the bounds of an array
Trying to store a value into an array of an incompatible class or type
Trying to cast an instance of a class to one of its subclasses
Passing a parameter that is not in a valid range or value for a method
Trying to illegally change the state of a thread
Attempting to use a negative size for an array
Using a null object reference as a legitimate object reference to access a method or a variable
Converting invalid string to a number
Accessing a character that is out of bounds of a string
And many more
PARNASHREE S, SKPFGC Page 1
UNIT 3
Exceptions:
An exception is a condition that is caused by a run-time error in the program. When the Java
interpreter encounters an error such as dividing an integer by zero, it creates an exception object and
throws it (i.e., informs us that an error has encountered).
If the exception object is not caught and handles properly, the interpreter will display an error
message and terminate the program. If we want the program to continue with the execution of the
remaining code, then we should try to catch the exception object thrown by the error condition and
then display an appropriate message for taking corrective actions. This task is known as exception
handling.
The purpose of exception handling mechanism is to provide a means to detect and report an “exceptional
circumstances” so that appropriate action can be taken. The mechanism suggests incorporation of a
separate error handling code that performs the following tasks:
1. Find the problem (Hit the exception).
2. Inform that an error has occurred (Throw the exception).
3. Receive the error information (Catch the exception).
4. Take corrective actions (Handle the exception).
The error handling code basically consists of two segments, one to detect errors and to throw exception
and the other to catch exceptions and to take appropriate actions.
Common Java Exceptions: Different types of exceptions
Exception Type Cause of Exception
ArithmeticException Caused by math errors such as division by zero
ArrayIndexOutOfBoundsException Caused by bad array indexes
ArrayStoreException Caused when a program tries to store the wrong type of data in an
array
FileNotFoundException Caused by an attempt to access a nonexistent file
IOException Caused by general I/O failures, such as inability to read from a file
NullPointerException Caused by referencing a null object
NumberFormatException Caused when a conversion between strings and number fails
OutOfMemoryException Caused when there’s not enough memory to allocate a new object
SecurityException Caused when an applet tries to perform an action not allowed by
the browser’s security setting.
StackOverflowException Caused when the system runs out of stack space
StringIndexOutOfBoundsException Caused when a program attempts to access a nonexistent character
position in a string
PARNASHREE S, SKPFGC Page 2
UNIT 3
Syntax of Exception handling code:
The basic concepts of exception handling are throwing an exception and catching it. This is illustrated in
below fig.
try Block
Exception object
Statement that
creator
causes an exception
throws
exception object
catch Block
Statement that Exception
handles the exception handler
fig: Exception handling mechanism
Java uses a keyword try to preface a block of code that is likely to cause an error condition and
“throw” an exception.
A catch block defined by the keyword catch “catches” the exception “thrown” by the try block
and handles it appropriately. The catch block is added immediately after the try block. The
following example illustrates the use of simple try and catch statements.
………………….
………………….
try
{
statement; // generates an exception
}
catch(Exception-type e)
{
Statement; // processes the exception
}
………………….
………………….
The try block can have one or more statements that could generate an exception. If any one statement
generates an exception, the remaining statements in the block are skipped and execution jumps to the
catch block that is placed next to try block.
PARNASHREE S, SKPFGC Page 3
UNIT 3
The catch block too can have one or more statements that are necessary to process the exception.
Remember that every try statements should be followed by at least one catch statement; otherwise
compilation error will occur.
Note that the catch statement works like a method definition. The catch statement is passed a single
parameter, which is reference to the exception object thrown (by the try block). If the catch parameter
matches with the type of exception object, then the exception is caught and statements in the catch block
will be executed. Otherwise, the exception is not caught and the default exception handler will cause the
execution to terminate.
Program: Illustrates the use of try and catch blocks to handle an arithmetic exception.
class Error3
{
public static void main(String args[ ])
{
int a = 10;
int b= 5;
int c = 5;
int x, y;
try
{
x = a/(b-c); // Exception here
}
catch(ArithmeticException e)
{
[Link](“division by zero”);
}
y = a/(b+c);
[Link](“y = ” +y);
}
}
Output:
Division by zero
y=1
Note that the program did not stop at the point of exceptional condition. It catches the error condition,
prints the error message, and then continues the execution, as if nothing has happened.
PARNASHREE S, SKPFGC Page 4
UNIT 3
Multiple catch statements:
It is possible to have more than one catch statement in the catch block as illustrated below:
……………..
……………..
try
{
statement; // generates an exception
}
catch(Exception-Type-1 e)
{
statement; // produces exception type 1
}
catch(Exception-Type-2 e)
{
statement; // produces exception type 2
}
.
.
.
catch(Exception-Type-N e)
{
statement; // produces exception type N
}
……………..
……………..
When an exception in a try block is generated, the Java treats the multiple catch statements like cases in a
switch statement. The first statement whose parameter matches with the exception object will be
executed, and the remaining statements will skipped.
Note that Java does not require any processing of the exception at all. We can simply have a catch
statement with an empty block to avoid program abortion.
Example:
catch(Exception e);
The catch statement simply ends with a semicolon, which does nothing. This statement will catch an
exception and then ignore it.
PARNASHREE S, SKPFGC Page 5
UNIT 3
Program: Using multiple catch blocks.
class Error4
{
public static void main(String args[ ])
{
int a[ ] = {5,10};
int b = 5;
try
{
int x=a[2]/b-a[1];
}
catch(ArithmeticException e)
{
[Link]("division by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array index error");
}
catch(ArrayStoreException e)
{
[Link]("wrong data type");
}
int y=a[1]/a[0];
[Link]("y = " +y);
}
}
Output:
Array index error
y=2
Note that the array element a[2] does not exist because array a is defined to have only two elements, a[0]
and a[1]. Therefore, the index 2 is outside the array boundary thus causing the block
catch(ArrayIndexOutOfBoundsException e)
to catch and handle the error. Remaining catch blocks are skipped.
Using finally statement:
Java supports another statement known as finally statement that can be used to handle an exception that is
not caught by any of the previous catch statements.
finally block can be used to handle any exception generated within a try block. It may be added
immediately after the try block or after the last catch block shown as follows:
PARNASHREE S, SKPFGC Page 6
UNIT 3
1. try
{
……………..
……………..
}
finally
{
……………..
……………..
}
2. try
{
……………..
……………..
}
catch(….)
{
……………..
……………..
}
catch(….)
{
……………..
……………..
}
.
.
.
finally
{
……………..
……………..
}
When a finally block is defined, this is guaranteed to execute, regardless of whether or not an exception is
thrown. As a result, we can perform certain house-keeping operations such as closing files and releasing
system resources.
PARNASHREE S, SKPFGC Page 7
UNIT 3
User defined Exception using try-catch-finally-throw blocks (Throwing our own exceptions):
In Java, a user-defined exception is a custom exception created by extending the Exception
class (or one of its subclasses). This allows you to define specific types of errors that are relevant
to your application. You can create your own exceptions when the built-in exceptions don't meet
your needs.
Steps to create a user-defined exception:
1. Create a class that extends Exception (for checked exceptions) or RuntimeException
(for unchecked exceptions).
2. Define constructors in the custom exception class to pass messages or other information.
We can do this by using the keyword throw as follows:
throw new Throwable_subclass;
throw new ArithmeticException( );
throw new NumberFormatException( );
Note: throw Keyword in Java
The throw keyword in Java is used to explicitly throw an exception. It is different from throws, which is
used in method signatures to declare exceptions.
Below program demonstrates the use of a user-defined subclass of Throwable class. Note that Exception
is a subclass of Throwable and therefore MyException is a subclass of Throwable class. An object of a
class that extends Throwable can be thrown and caught.
Example Program: Throwing our own Exception
import [Link];
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
class TestMyException
{
public static void main(String args[ ])
{
int x = 5, y = 1000;
try
PARNASHREE S, SKPFGC Page 8
UNIT 3
{
float z = (float)x/(float)y;
if(z < 0.01)
{
throw new MyException("Number is too small");
}
}
catch(MyException e)
{
[Link]("caught my exception");
[Link]([Link]( ));
}
finally
{
[Link]("I am always here");
}
}
}
Output:
Caught my exception
Number is too small
I am always here
Nested Try Blocks in Java
A nested try block is a try block inside another try block. This is useful when handling multiple levels of
exceptions, where an inner block might handle specific exceptions, and the outer block handles more
general ones.
public class NestedTryExample {
public static void main(String[] args) {
try {
[Link]("Outer try block started.");
try {
int[] arr = {1, 2, 3};
[Link](arr[5]); // This will cause an ArrayIndexOutOfBoundsException
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Inner catch: Array index is out of bounds!");
}
// This statement will still execute because the inner exception was handled.
int result = 10 / 0; // This will cause an ArithmeticException
}
PARNASHREE S, SKPFGC Page 9
UNIT 3
catch (ArithmeticException e) {
[Link]("Outer catch: Cannot divide by zero!");
}
[Link]("Program continues...");
}
}
OUTPUT:
Outer try block started.
Inner catch: Array index is out of bounds!
Outer catch: Cannot divide by zero!
Program continues...
throws Keyword in Java
The throws keyword in Java is used in method declarations to specify that a method might throw one or
more exceptions. It informs the caller of the method that it must handle or propagate these exceptions.
Syntax of throws
returnType methodName(parameters) throws ExceptionType1, ExceptionType2
{
// Method code
}
throws is used in the method signature.
It is followed by one or more exception types, separated by commas.
Example: Using throws with a Built-in Exception
public class ThrowsExample {
static void divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero!");
}
[Link]("Result: " + (a / b));
}
public static void main(String[] args) {
try {
divide(10, 2); // Works fine
divide(10, 0); // Throws an exception
} catch (ArithmeticException e) {
[Link]("Caught Exception: " + [Link]());
}
}
}
Output:
Result: 5
Caught Exception: Cannot divide by zero!
PARNASHREE S, SKPFGC Page 10