Basics of Exceptions
by, 11-29-2011 at 03:09 AM (1094 Views)
One of the key aspects of programming is understanding how to handle exceptions. An exception is a problem that prevents the continuation of the current method or scope. Itís important to distinguish an exceptional condition from a normal problem, in which you have enough information in the current context to somehow cope with the difficulty. With an exception, you cannot continue processing because you lack the information necessary to address the problem in its current context. The only recourse you have, is to jump out of the current context and relegate that problem to a another (higher) context.
When you throw an exception, there are several things taking place. First, the exception object is created on the heap, with new keyword. The current path of execution is stopped and the reference for the exception object is ejected from the current context. At this point the exception-handling mechanism kicks in and you define the context for the exception to be handled in a manner in a way that is safe for the program and in which can you provide appropriate information to the user. The means of appropriate means Java has for this is what is called an exception handler. An exception handler is used to recover from a problem so the program can either try another tack or just continue.
The way you do this is by throwing an exception. What throwing an exception does is to put the error into a larger context by creating an object representing your information and "throwing" it out of its existing context. Here is an example:
In the example has an object reference called t. In this situation because it hasnít been initialized it has a null reference. Because of that it is impossible to go further with processing so a NullPointerException is thrown. Exceptions allow you to force the program to stop and tell you what went wrong, or (ideally) force the program to deal with the problem and return to a stable state.Java Code:if(t == null) throw new NullPointerException();