Chapter 10 |
Introduction
An exception (or exceptional event) is a problem that arises during the execution of a program. When an unhandled exception occurs, the normal flow of the program is disrupted and the program terminates abnormally. Such situations are not recommended.
An exception can occur for many different reasons. For example: opening a non-existing file in the program, network connection problem, bad input data provided by user, etc. Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.
Run the following program which contains some errors and study the output messages:
int[] myNumbers = { 1, 2, 3 }; System.out.println(myNumbers[42]); // ArrayIndexOutOfBoundsException int n = Integer.parseInt("text"); // NumberFormatException String myString = null; myString.length(); // NullPointerException
The output of the program is not user friendly. Most probably a user will not be able to understand what went wrong. In order to let the user know the reason in simple language, exceptions has to be handled so that a user friendly warning message is printed out. Exception handling ensures that the flow of the program doesn’t break when an exception occurs.
Chapter 10 |