Introduction to Exception Handling
When designing computer programs, you need to plan for the possibility of the program failing due to the occurrence of events at run time. Examples of such events might include trying to gain access to a cell of an array through a subscript that exceeds the permitted range, dividing a number by zero in an arithmetic computation, attempting to open a file that does not exist, and so on. The full list of events that can cause a program to malfunction is quite considerable!
An exception is an event that occurs during the execution of a program that disrupts the normal flow of control.
An exception is an event occurring during the execution of a program that makes continuation impossible or undesirable. Examples of exceptions include division by zero, arithmetic overflow, array reference with an index out of bounds, or a fault condition on a peripheral. Many programming languages respond to an exception by aborting execution. However, one of the design goals of Java was to provide the language with sufficient features to enable the programmer to write robust programs. An exception handler is a piece of program code that is automatically invoked when an exception occurs. The exception handler can take appropriate remedial action, then either allow resumption of the execution of the program (at the point where the exception occurred or elsewhere) or terminate the program in a controlled manner.
Syntax
Try {
//Code which may generate error
statement(s);
} catch (Exception e) {
//Handle error
statement(s);
}
Example
1. /**
2. * @(#)ExceptionDemo.java
3. *
4. *
5. * @author
6. * @version 1.00 2009/11/23
7. */
8.
9. public class ExceptionDemo {
10.
11. /**
12. * Creates a new instance of <code>ExceptionDemo</code>.
13. */
14. public ExceptionDemo() {
15. }
16.
17. /**
18. * @param args the command line arguments
19. */
20. public static void main(String[] args) {
21. // TODO code application logic here
22.
23. int a = 75;
24. int b = 0;
25.
26. int c = 0;
27.
28. try {
29.
30. //Code which generates an exception
31. c = a / b;
32.
33. } catch (ArithmeticException ae) {
34.
35. //Perform appropriate action when an error is occurred.
36.
37. System.out.println("Exception " + ae.getMessage() + " caught.");
38.
39. }
40.
41. System.out.println("nException is handled successfully.");
42.
43. }
44. }
Output
Exception / by zero caught.
Exception is handled successfully.
In above example, the exception handling code is from line 28 to 39. Normally in Java, when we divide a value by zero, program generates an exception and the program is terminated. An exception is also generated in the above program but the program doesn’t not terminate because we have caught exception properly.
