Java Exception Handling Mechanism
Java Exception Handling Mechanism
From
[ Web Technology ]
For Continuous Assessment 2(CA 2)
Under
MAULANA ABUL KALAM AZAD UNIVERSITY OF TECHNOLOGY
(Formerly known as West Bengal University of Technology)
Submitted by
1
TABLE OF CONTENTS
1 Introduction 3
2 Exception Hierarchy 4
6 Conclusion 11
2
Introduction
Exception Handling in Java is one of the effective means to handle the
runtime errors so that the regular flow of the application can be preserved.
Java Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException,
etc.
Exception is an unwanted or unexpected event, which occurs during the
execution of a program, i.e. at run time, that disrupts the normal flow of the
program’s instructions. Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object. This object is
called the exception object. It contains information about the exception, such
as the name and description of the exception and the state of the program when
the exception occurred.
Major reasons why an exception Occurs
Invalid user input
Device failure
Loss of network connection
Physical limitations (out of disk memory)
Code errors
Opening an unavailable file
Errors represent irrecoverable conditions such as Java virtual machine (JVM)
running out of memory, memory leaks, stack overflow errors, library
incompatibility, infinite recursion, etc. Errors are usually beyond the control of
the programmer, and we should not try to handle errors.
Let us discuss the most important part which is the differences between
Error and Exception that is as follows:
Error: An Error indicates a serious problem that a reasonable application
should not try to catch.
Exception: Exception indicates conditions that a reasonable application
might try to catch.
Exception Hierarchy
All exception and error types are subclasses of class Throwable, which is the
base class of the hierarchy. One branch is headed by Exception. This class is
used for exceptional conditions that user programs should catch.
NullPointerException is an example of such an exception. Another
branch, Error is used by the Java run-time system (JVM) to indicate errors
having to do with the run-time environment itself(JRE). StackOverflowError is
an example of such an error.
3
Exception Hierarchy
Here, the class Throwable is used to represent all exceptional conditions. Two
immediate subclasses of Throwable are Exception, and Error. The class
Exception is used for exceptional conditions that user programs can catch. The
other branch of the throwable tree is the class Error, which defines the
conditions that should not be expected to be caught under normal
circumstances. These class is responsible for giving errors in some catastrophic
failures. A further refinement is there by a sub class of Exception, which is for
exceptional condition that created by the run time called RuntimeException.
These exceptions are typically created automatically during the run time in
response to some execution error. A list of exceptions that a programmer can
catch in the program is summarized below:
4
RuntimeException sub classes: Error sub classes:
ArithmeticException ClassCirculatoryError
ArrayIndexOutofBoundException ClassFormatError
ArrayStoreException Error
ClassCasteException IllegalAccessError
IlegalArgumentException IncompatibleClassChangeError
IndexOutofBoundException InstantiationError
NegativeArraySizeException LinkageError
NullPointerException NoCassDefFoundError
NumberFormatException NoSuchFieldError
SecurityException NoSuchMethodError
StringIndexOutofBoundException OutofMemoryError
StackOverflowError
Exception sub classes: Throwable
ClassNotFoundException UnknownError
DataFormatException UnsatisfiedLinkError
IllegalAccessException VerifyError
InstantiationException VirtualMachineError
InterruptedException
NoSuchMethodException
RuntimeException
5
Mechanism of Exceptions Handling in Java
Java's exception handling brings Run Time Error Management into the object-
oriented world. During the execution of a program, when an exceptional
condition arises, an object of the respective exception class is created and
thrown in the method which caused the exception. That method may choose to
catch the exception and then can guard against premature exit or may have a
block of code execute.
Java exception handling is managed via five key words: try, catch, throw,
throws, and finally. Here is the basic form of an exception handling block.
try-catch:
try {
// block of code
}
catch (ExceptionType1 e) {
// Exception handling routine for ExceptionType1 (optional)
}
catch (ExceptionType2 e) {
// Exception handling routine for ExceptionType2 (optional)
}
.
.
.
catch (ExceptionType_n e) {
// Exception handling routine for ExceptionType_n (optional)
}
finally {
// Program code of exit (optional)
}
6
throws:
��..
anArray[10] = 999 ; // index out of range
}
7
ArrayStoreException : This exception occurs when one try to store a value
into an array of incompatible class or type. Following is an example where
ArrayStoreException will be thrown.
void badArrayStore ( ) {
int storeArray = new int[15]; // An array of
integers
boolean boolArray =new boolean[5]; // An array of
booleans
System.arraycopy(storeArray, 2, boolArrary, 2, 4);
// Copy the element boolArray[3,4,5]
into storeArray starting at storeArray[2]
}
���
}
���.
void bMethod ( ) { . . . . }
}
class Test {
void wrongCast ( ) {
ClassA anInstanceA = new ClassA( );
ClassB anInstanceB = (Class B ) anInstanceA; // Exception
anInstanceB.bMethod ( );
}
}
8
The following method throws an IllegalArgumentException if passed an illegal
parameter value:
static void wrongArgumentPass (int agru) {
if (argu == 0)
throw new IllegalArgumentException ( "Argument cannot be 0 ");
int x = 555 / argu;
}
9
SecurityException : This exception is thrown by some methods in the System
package when one attempt to call a method that will perform an action not
allowed by the current security settings of the browser within which the applet
code is running. It can also be thrown if the program denies permission when
prompted whether to allow an action such as writing to a file.
StringIndexOutOfBoundsException: A StringIndexOutOfBoundsException
is thrown when one try to access a character that is out of the bounds of a string,
meaning that using an index of less than zero or greater than or equal to the
length of the string. Following is an example that would throw a
StringIndexOutOfBoundException:
void wrongStringIndex ()
{
String theString = " N E R I S T",
char theChar = theString.charAt(20); // Index should be between 0 and 1
}
10
Conclusion
From the above few examples and statements we can conclude that:
In a method, there can be more than one statement that might throw an
exception, So put all these statements within their own try block and
provide a separate exception handler within their own catch block for each
of them.
If an exception occurs within the try block, that exception is handled by the
exception handler associated with it. To associate the exception handler, we
must put a catch block after it. There can be more than one exception
handlers. Each catch block is an exception handler that handles the
exception to the type indicated by its argument. The argument,
ExceptionType declares the type of exception that it can handle and must
be the name of the class that inherits from the Throwable class.
For each try block, there can be zero or more catch blocks, but only
one final block.
The finally block is optional. It always gets executed whether an exception
occurred in try block or not. If an exception occurs, then it will be executed
after try and catch blocks. And if an exception does not occur, then it will
be executed after the try block. The finally block in java is used to put
important codes such as clean up code e.g., closing the file or closing the
connection.
11