Java Exception Handling Mechanism

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

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

NAME: Anubhav Dutta


REGISTRATION NUMBER: 040790 OF 2019-20
ROLL NUMBER: 10200319037
DEPARTMENT: ECE
YEAR: 4th
SEMESTER: 7th

KALYANI GOVERNMENT ENGINEERING COLLEGE


KALYANI

1
TABLE OF CONTENTS

Sl. No. Title Pg. No.

1 Introduction 3

2 Exception Hierarchy 4

5 Mechanism of Exceptions Handling in Java 6

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

To handle the common possible exceptions, Java defined a class hierarchy as


shown below:

Exception Class hierarchy in Java

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:

return_type method_name() throws exception_class_name{


//method code
}

Error Handling Exception Classes


In previous Section of this Chapter, we have listed the different classes for
handling exceptions in Java. In this Section, let us get a brief introduction about
the main of them :
ArithmeticException: An ArithmeticException is thrown if one try to divide
an integer by zero or take a modules by zero. For example, the following code
causes an ArithmeticException to be thrown:
int wrongMath ( ) {
int n = 100;
int result ;
for (int i = 9; i > -1; i- - )
result = n % i; // modulo remainder.
return (result );
}

ArrayIndexOutofBoundsException : In ArrayIndexOutofBoundsException is


thrown when one try to access an array element that is out of bounds, meaning
that one using an index of less than zero or greater than or equal to the size of
the array. Here is a token example that would throw an
ArrayIndexOutofBoundsException :
void wrongArrayAccess ( ) {
int anArray = new int[10] ; // An array of size having index
0,1,..,9

��..
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]
}

ClassCastException : In Java, an instance of a class of one type can be


possible to cast for another type. Here an instance of class can be casted to its
super class but one can not cast an instance of class to its subclasses. If one
attempt this cast, a ClassCasteException will occur. The following example,
results a ClassCastException at run time :
class ClassA { // a token of a simple class

���
}

class ClassB extends ClassA{ // A sub class of ClassA

���.
void bMethod ( ) { . . . . }
}

class Test {
void wrongCast ( ) {
ClassA anInstanceA = new ClassA( );
ClassB anInstanceB = (Class B ) anInstanceA; // Exception
anInstanceB.bMethod ( );
}
}

IllegalArgumentException: This IllegalArgumentException occurs when one


attempt to pass a parameter that is not in valid range or value for the method.

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;
}

Not that, in the above example, method wrongArgumentPass(int) throws an


exception when caller passes unacceptable value.
IllegalThreadStateException: This exception is thrown by some methods in
the system package classes when one try to illegally change the state of thread,
for example, by trying to start a thread that is already running.
IndexOutofBoundsException: This exception can be thrown in a method
when one passed an index value that is outside an acceptable range.
NegativeArraySizeException: This exception is thrown when an array with a
negative size is attempted to be allocated. The following method results in a
NegativeArraySizeException at run time:
Void negativeSizeArray () {
int theSize = -5;
int foolArray = new int[theSize];
}

NullPointerException: This exception is thrown when one attempt to use a


method or variable in a variable name that contains a null object reference. The
following method results in a NullPointerException at run time:
void nullPointer ()
{
String myString = null; // myString is a null reference object
if (myString.equals (" Sahara" )) {
System.out.println (" Howz!");
}
}

NumberFormatException : This exception is thrown by some methods in


classes of System package when one try to convert an invalid string to a number
or vice versa.

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
}

ClassNoFoundException : This exception is thrown by the class loader when a


class file is not found when a class is attempted to be instantiated.
DataFormatException : This exception is thrown when data being read from a
string appears to be in an invalid format.
IllegalAccessException : This exception is thrown by methods in java.lang
class when instantiating a class by its name if the class is not public or there is
no public constructor. One might encounter this exception if calling a method
that, in turn, calls one of these methods.
InstantiationException : This exception is thrown when an attempt is made to
instantiate an abstract class, primarily by methods in java.lang class when
instantiating a class by its name.
InterruptedException : This exception is thrown within a thread when it is
interrupted by some other thread. This exception will be illustrated during the
discussion of Thread in Java.
NoSuchMethodException : This exception is thrown when a particular method
in an object or class cannot be found.

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

You might also like