Friday, 14 October 2016

Exception handling

By,
Praveen



An exception is an abnormal condition that occurs during the execution of a program.
It is common to make errors while developing or typing a program. And this may cause the program to produce unexpected results.
It is therefore necessary to detect and manage the error conditions in the program so that the program will not terminate during the execution.

Types of Errors:
1.      Compile time error:
All syntactical errors are detected and displayed by the compiler and so they are called as compile-time errors.And when the complier detects such an error, it will not create .class file.
The most common compile-time errors are:
·         Missing semicolons
·         Mismatch of brackets
·         Use of undeclared variables
·         Use of = in place of == operator
2.      Run-time errors:
Sometimes, the program is compiled successfully but may not run properly.
Most common run –time errors are –
·         Dividing an integer by zero
·         Trying to illegally change the state of the thread
·         Accessing an element that is out of the bounds of an array
Java has a special mechanism for handling such type of errors. The code that is prone to generate such errors should be written in the try block and the errors can be handled in the catch block. The catch statement needs a special parameter which indicates the type of error it is supposed to handle. The mechanism is known as Exception handling.
Exception Keywords:
These exception are also called checked error since it is system defined i.e. in –built exception.
Exception handling in java is associated with following keywords:
1.      Try(find the problem)
2.      Throw (inform that an error has occurred)
3.      Catch(receive the error information)
4.      Finally(handle the exception by taking corrective actions)


Common Java Exceptions:
ArithmeticException :
Caused by math errors such as division by zero.
ArrayIndexOutOfBoundsException:
                                                       Caused by bad indexes.
FileNotFoundException:
                                            Caused by an attempt to access non-existent file.
EOFxception:
                       Caused by an attempt to read the end-of file.
NullPointerException:
                                       Caused by referencing a null object.
NumberFormatException:
                                              Caused by the failure in the conversion between string and numbers.
NegativeArraysizeException:
                                                       When array is negative.
SQLException:
                        Caused due to an error during a database access.
Try and Catch:
The advantage of using the try and catch keywords are that, It fixed the error and prevents the program from terminating abruptly.
The general form is:
try{
// To do code
}
Catch(Exception-type e)
{
//exception handling code
}





No comments:

Post a Comment