Exception handlingIn computing, an exception is a special situation where the program cannot do things the way it usually would and is forced to do something else instead. One layer of the system uses an exception to give another layer information about special states the system is currently in. The different layers of software or hardware have contracts, that tell what can be expected; this is generally known as Programming by Contract. In the context of exception handling, a program is said to be exception-safe, if exceptions that occur will not produce side-effects (such as memory leaks), will not change stored data so that it becomes unreadable, or generate output that is invalid. There are different levels of exception safety:
Usually, a programmer will try to catch the exception early so that problems don't get worse over time. ExampleSuppose a program tries to add something to an array, or group of objects that doesn't exist. This is called a null reference. Look at the following code from the Java programming language: class SomeProgram {
int[] SomeArray = null; // This array of numbers doesn't exist
public static void main(String[] args) {
System.out.println("The 1st number in the array is " + SomeArray[0] + "."); // This will throw an exception because it refers to an imaginary array
}
}
This code throws what programmers call a null-pointer exception. This is fixed by adding " class AnotherProgram {
int[] SomeArray = null; // This array of numbers doesn't exist
public static void main(String[] args) {
try {
System.out.println("The 1st number in the array is " + SomeArray[0] + "."); // This will throw an exception because it
// refers to an imaginary array
}
catch (NullPointerException e) { // This is how you catch a null-pointer exception
System.err.println("Sorry. I could not find the first number in the array."); // This creates an error message
e.printStackTrace(); // This tells you where to look for bugs in your program
}
}
}
Related pagesReferences
|