Chapter 7 Exception Handling




Chapter 7  Exception Handling
Rarely does a program run successfully at its very first attempt. It is common to make mistakes while developing as well as typing a program. A mistake might lead to an error causing the program to produce unexpected result. Errors are the wrong that can make a program go wrong.
Errors may broadly be classified into two categories :
1. Compile - time error :
All syntax errors will be detected and displayed by the java compiler and therefore error are know as compile - time errors. Whenever the compiler displays an error, it will not create the .class file. It is there fore necessary that we can successfully compile and run the program.
Example :
class error1
{
public static void main (String args[])
{
System.out.println("hello java")// missing ;
}
}

2. Run - time error :
Sometimes, a program may compile successfully creating the .class file but may not run properly. Such programs may produce wrong results due to wrong logic or may terminate due to errors such as dividing an integer by zero. These errors are called run-time error.
Example :
class error2
{
public static void main (String args[])
{
int a=10;
int b=5;
int c=5;
int x=a/(b-c);
.....
//Division by zero
}
}
Exceptions :
An exception is a condition that is caused by a run-time error in the program. If the exception object is not caught and handle properly, the interpreter will display an error message and will terminate the program.
The basic concepts of exception handling are throwing an exception and catching it. This is illustrated in fig.