An exception is a condition that is caused by a run-time error . when java interpreter encounter an error such as dividing an integer by zero, then it creates an exception and throw it informs us that error has occurred. If that exception is not handled or caught , the interpreter will display an error message and terminate the program. If we want to avoid this and program to continue with execution of remaining code, then we should try to catch the exception. This is known as exception handling
The exception handling consist of two segments , one to detect errors and throw exception and the other to catch exceptions and to take appropriate actions.
Some common exceptions that are occurred during the program listed as follows
1)ArithmeticException
|
Caused by math errors like division by zero
|
2)ArrayStoreException
|
Caused when a program tries to store the wrong type of data in array
|
ArrayIndexOutOfBoundException
|
Caused by bad index of array
|
FileNotFoundException
|
Caused when attempt to access a file that is not exist
|
IOException
|
Caused by general I/O failure
|
OutOfMemoryException
|
When not enough memory to allocate a new object
|
NullPointerException
|
Caused by referencing a null object
|
NumberFormatException
|
Caused when a conversion between strings and number fails
|
Syntax for Exception handling code
There is try keyword in java that is used for exception handling . All the statement s which are likely to generate an exception put in try block and catch block is define by catchkeyword that catches the exception thrown by try block.
Syntax is as follows
try{
statement; // generates an exception
}
catch(Exception_type e)
{
Statement //processes the exception
}
More than one catch statement
It is possible to have more than one catch statements in a program corresponding to single try statement. Example is as follows
class test1{
public static void main(String args[]){
int a[]={2,4};
int b=2;
try{
int x=a[2]/b-a[1];
}
catch(ArithmeticException e){
System.out.println(“Division by zero”);
}
Catch(ArrayIndexOutOfBoundException e)
{
System.out.println(“Array index error”);
}
Catch(ArrayStoreException e)
{
System.out.println(“Array index error”);
}
Int y=a[1]/a[0];
System.out.println(”y = ” +y);
}
}
Use of Finally statement
Java supports another statement known as finally for exception handling . finally block may be added immediately after the try block or after the last catch block. Defining a finally block is guaranteed to execute statement under the finally block , regardless of whether or not in exception is thrown.
In the above program we may include the last two statements inside a finally block as shown below.
finally
{
Int y=a[1]/a[0];
System.out.println(”y = ” +y);
}