Exception handling
From Wikipedia, the free encyclopedia
A computer program will sometimes throw an exception, which is a special situation where the program cannot do things the way it usually would and is forced to do something else instead. Usually, a programmer will try to catch the exception early so that problems don't get worse over time.
Example [change]
Suppose 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 "try" in front of the code that might throw the exception, like is done with the code shown below:
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 } } }