Tuesday, October 7, 2008

JAVA PROGRAMMING/EXCEPTIONS

In Java, there are two main flow of code executions.

Normal main sequential code execution, the program doing what it meant to accomplish
Exception handling code execution, the main program flow was interrupted by an error or some other condition that prevent the continuation of the normal main sequential code execution.
Exception
Exceptions are Java's way of error handling. Whenever an unexpected condition occurs, an exception can be thrown with an exception object as a parameter. It means that the normal program control flow stops and the search for a catch block begins. If that is not found at the current method level the search continues at the caller method level, until a matching catch block is found. If none is found the exception will be handled by the JVM, and usually the java program terminates.
When a catch "matching" block is found, that block will be executed, the exception object is passed to the block as a parameter. Then normal program execution continues after the catch block. See Java exception handling syntax
Exception Object
This is the object that is "thrown" as a parameter from the error, and passed to the catch block. Exception object encapsulates the information about the error's location and its nature. All Exception objects must be inherited from the java.lang.Throwable. See the UML diagram below.
Matching rule
A thrown exception object can be caught by the catch keyword and specifying the exception object's class or its super-class.
Naming convention
It is good practice to add Exception to all exception classes. Also the name of the exception should be meaningful, should represent the problem. For example CustomerNotFoundException indicate that customer was not found.

No comments: