Exception Handling(27!03!25)
Exception Handling(27!03!25)
An exception in java programming is an abnormal situation that is araised during the program
execution. In simple words, an exception is a problem that arises at the time of program
execution.
When an exception occurs, it disrupts the program execution flow. When an exception
occurs, the program execution gets terminated, and the system generates an error. We use the
exception handling mechanism to avoid abnormal termination of program execution.
Java programming language has a very powerful and efficient exception handling mechanism
with a large number of built-in classes to handle most of the exceptions automatically.
Java programming language has the following class hierarchy to support the exception
handling mechanism.
import java.io.*;
}
}
Unchecked Exceptions
The unchecked exception is an exception that occurs at the time of program execution. The
unchecked exceptions are not caught by the compiler at the time of compilation.
The unchecked exceptions are generally caused due to bugs such as logic errors, improper
use of resources, etc.
The following are a few built-in classes used to handle unchecked exceptions in java.
ArithmeticException
NullPointerException
NumberFormatException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
_↓ In the exception class hierarchy, the unchecked exception classes are the children of
RuntimeException class, which is a child class of Exception class.
The unchecked exception is also known as a runtime exception.
Let's look at the following example program for the unchecked exceptions.
Example - Unchecked Exceptions
System.out.println(list[6]);
//ArrayIndexOutOfBoundsException
String msg=null;
System.out.println(msg.length()); //NullPointerException
String name="abc";
int i=Integer.parseInt(name); //NumberFormatException
}
Resumptive Model
The alternative of termination model is resumptive model. In resumptive model, the
exception handler is expected to do something to stable the situation, and then the faulting
method is retried. In resumptive model we hope to continue the execution after the exception
is handled.
In resumptive model we may use a method call that want resumption like behavior. We may
also place the try block in a while loop that keeps re-entering the try block util the result is
satisfactory.
import java.util.Scanner;
}
}
When we execute the above code, it produce the following output for the value a = 10 and b
= 0.
In the above example code, we are not used try and catch blocks, but when the value of b is
zero the division by zero exception occurs and it caught by the default exception handler.
In java, the trytry and catch, both are the keywords used for exception handling.
The keyword try is used to define a block of code that will be tests the occurence of an
exception. The keyword catch is used to define a block of code that handles the exception
occured in the respective try block.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Both try and catch are used as a pair. Every try block must have one or more catch blocks.
We cannot use try without atleast one catch, and catch alone can be used (catch without try is
not allowed).
The following is the syntax of try and catch blocks.
Syntax
try{
...
code to be tested
...
}
catch(ExceptionType object){
...
code for handling the exception
...
}
Consider the following example code to illustrate try and catch blocks in Java.
Example
import java.util.Scanner;
try {
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[10] = list[2] / list[4];
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor can not be ZERO.");
}
catch(ArrayIndexOutOfBoundsException aie) {
System.out.println("Problem info: ArrayIndexOutOfBoundsException has occured.");
}
catch(Exception e) {
System.out.println("Problem info: Unknown exception has occured.");
}
}
}
try {
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[0] = list[2] / list[4];
try {
list[10] = 100;
}
catch(ArrayIndexOutOfBoundsException aie) {
System.out.println("Problem info: ArrayIndexOutOfBoundsException has
occured.");
}
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor can not be ZERO.");
}
catch(Exception e) {
System.out.println("Problem info: Unknown exception has occured.");
}
}
}
_ In case of nested try blocks, if an exception occured in the inner try block and it's catch
↓
blocks are unable to handle it then it transfers the control to the outer try's catch block to
handle it.
In java, the keywords throw, throws, and finally are used in the exception handling concept.
Let's look at each of these keywords.
throw keyword in Java
The throw keyword is used to throw an exception instance explicitly from a try block to
corresponding catch block. That means it is used to transfer the control from try block to
corresponding catch block.
The throw keyword must be used inside the try block. When JVM encounters the throw
keyword, it stops the execution of try block and jump to the corresponding catch block.
↓_ Using throw keyword only object of Throwable class or its sub classes can be thrown.
_↓ Using throw keyword only one exception can be thrown.
_↓ The throw keyword must followed by an throwable instance.
The following is the general syntax for using throw keyword in a try block.
Syntax
throw instance;
Here the instace must be throwable instance and it can be created dynamically using new
operator.
Let's look at the following example Java code to illustrate throw keyword.
Example
import java.util.Scanner;
The throws keyword does the same thing that try-catch does but there are some cases where
you would prefer throws over try-catch. For example: Lets say we have a method
myMethod() the statements inside this method can throw either ArithmeticException or
NullPointerException, in this case you can use try-catch as shown below:
One way to overcome this problem is by using throws like this: declare the exceptions in the
method signature using throws and handle the exceptions where you are calling this method
by using try-catch.
Another advantage of using this approach is that you will be forced to handle the exception
when you call this method, all the exceptions that are declared using throws, must be handled
where you are calling this method else you will get compilation error.
The throws keyword specifies the exceptions that a method can throw to the default handler
and does not handle itself. That means when we need a method to throw an exception
automatically, we use throws keyword followed by method declaration
_↓ When a method throws an exception, we must put the calling statement of method in try-
catch block.
Let's look at the following example Java code to illustrate throws keyword.
Example
public class ThrowsExample2
{
void division() throws ArithmeticException,ArrayIndexOutOfBoundsException
{
int list[]=new int[5];
list[2]=10;
list[4]=2;
list[0]=list[2]/list[4];
list[10]=100;
}
public static void main(String[] args)
{
try
{
new ThrowsExample2().division();
}
catch(ArithmeticException ae)
{
System.out.println("Problem info: divide by zero");
}
catch(ArrayIndexOutOfBoundsException aie)
{
System.out.println("Problem info: ArrayIndexOutOfBounds Exception");
}
}
}
Output:
Problem info: ArrayIndexOutOfBounds Exception
finally keyword in Java
The finally keyword used to define a block that must be executed irrespective of exception
occurence.
The basic purpose of finally keyword is to cleanup resources allocated by try block, such as
closing file, closing database connection, etc.
_↓ Only one finally block is allowed for each try block.
↓_ Use of finally block is optional.
Let's look at the following example Java code to illustrate throws keyword.
Example
import java.util.Scanner;
The Java programming language has several built-in exception class that support exception
handling. Every exception class is suitable to explain certain error situations at run time.All
the built-in exception classes in Java were defined a package java.lang.
1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and
the specified class cannot be found in the classpath.
2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been called to clone an
object, but that the object's class does not implement the Cloneable interface.
3 IllegalAccessException
It is thrown when one attempts to access a method or member that visibility qualifiers
do not allow.
4 InstantiationException
It is thrown when an application tries to create an instance of a class using the
newInstance method in class Class , but the specified class object cannot be instantiated
because it is an interface or is an abstract class.
5 InterruptedException
It is thrown when a thread that is sleeping, waiting, or is occupied is interrupted.
6 NoSuchFieldException
It indicates that the class doesn't have a field of a specified name.
S.
No. Exception Class with Description
7 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at
compile time, a NoSuchMethodException occurs during reflection when we try to
access a method that does not exist.
S.
No. Exception Class with Description
1 ArithmeticException
It handles the arithmetic exceptions like dividion by zero
2 ArrayIndexOutOfBoundsException
It handles the situations like an array has been accessed with an illegal index. The
index is either negative or greater than or equal to the size of the array.
3 ArrayStoreException
It handles the situations like when an attempt has been made to store the wrong type of
object into an array of objects
4 AssertionError
It is used to indicate that an assertion has failed
5 ClassCastException
It handles the situation when we try to improperly cast a class from one type to another.
6 IllegalArgumentException
This exception is thrown in order to indicate that a method has been passed an illegal or
inappropriate argument.
7 IllegalMonitorStateException
This indicates that the calling thread has attempted to wait on an object's monitor, or
has attempted to notify other threads that wait on an object's monitor, without owning
the specified monitor.
8 IllegalStateException
It signals that a method has been invoked at an illegal or inappropriate time.
9 IllegalThreadStateException
It is thrown by the Java runtime environment, when the programmer is trying to modify
the state of the thread when it is illegal.
10 IndexOutOfBoundsException
It is thrown when attempting to access an invalid index within a collection, such as an
S.
No. Exception Class with Description
11 NegativeArraySizeException
It is thrown if an applet tries to create an array with negative size.
12 NullPointerException
it is thrown when program attempts to use an object reference that has the null value.
13 NumberFormatException
It is thrown when we try to convert a string into a numeric value such as float or
integer, but the format of the input string is not appropriate or illegal.
14 SecurityException
It is thrown by the Java Card Virtual Machine to indicate a security violation.
15 StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is
either negative, or greater than the size of the string itself.
16 UnsupportedOperationException
It is thrown to indicate that the requested operation is not supported.