Thursday, November 6, 2008

Program to show How Exception Handling is in JAVA

Exception Handling: An exception is an error thrown by a class or method reporting an error in operation. Exceptions let you handle unusual error conditions without cluttering your code with nested ifs after every method call.

For example, dividing by zero is undefined in mathematics, and a calculation can fail if this winds up being the case because of an error in user input. In this particular case an ArithmeticException is thrown, and unless the programmer looks for this exception and manually puts in code to handle it, the program will crash stating the exception thrown and a stack trace, which would be unhelpful to a casual user of a Java program. If the programmer handles the exception, he could deliver a useful error to the user and return the user to the beginning of the program so that they could continue to use it.

Types of Exceptions in Java: Java defines two kinds of exceptions:
  • Checked exceptions: Exceptions that inherit from the Exception class are checked exceptions. Client code has to handle the checked exceptions thrown by the API, either in a catch clause or by forwarding it outward with the throws clause.

  • Unchecked exceptions: RuntimeException also extends from Exception. However, all of the exceptions that inherit from RuntimeException get special treatment. There is no requirement for the client code to deal with them, and hence they are called unchecked exceptions

The Nature of Exceptions: Broadly speaking, there are three different situations that cause exceptions to be thrown:
  • Exceptions due to programming errors: In this category, exceptions are generated due to programming errors (e.g., NullPointerException and IllegalArgumentException). The client code usually cannot do anything about programming errors.

  • Exceptions due to client code errors: Client code attempts something not allowed by the API, and thereby violates its contract. The client can take some alternative course of action, if there is useful information provided in the exception. For example: an exception is thrown while parsing an XML document that is not well-formed. The exception contains useful information about the location in the XML document that causes the problem. The client can use this information to take recovery steps.

  • Exceptions due to resource failures: Exceptions that get generated when resources fail. For example: the system runs out of memory or a network connection fails. The client's response to resource failures is context-driven. The client can retry the operation after some time or just log the resource failure and bring the application to a hal

Common Exceptions
There are many different exceptions that can be thrown by a program, and the Java API contains quite a few. A lot are contained in the default package, java.lang; however, when you start using more functionality such as AWT, Swing, or java.io, the packages may also contain additional exceptions thrown by those libraries. As you start expanding the functionality, it might be a good idea to look at potential exceptions in the package and when they might be thrown in the course of your application. Here is a primer of some:
  • ArithmeticException--thrown if a program attempts to perform division by zero
  • ArrayIndexOutOfBoundsException--thrown if a program attempts to access an index of an array that does not exist
  • StringIndexOutOfBoundsException--thrown if a program attempts to access a character at a non-existent index in a String
  • NullPointerException--thrown if the JVM attempts to perform an operation on an Object that points to no data, or null
  • NumberFormatException--thrown if a program is attempting to convert a string to a numerical datatype, and the string contains inappropriate characters (i.e. 'z' or 'Q')
  • ClassNotFoundException--thrown if a program can not find a class it depends at runtime (i.e., the class's ".class" file cannot be found or was removed from the CLASSPATH)
  • IOException--actually contained in java.io, but it is thrown if the JVM failed to open an I/O stream
"Catching" Exceptions :
The java language contains keywords used specifically for testing for and handling exceptions. The ones we will be using here are try and catch, and they must be used in conjunction with one another. They sort of work like if-else:

try{
/*
Contains code to be tested
*/
}catch(Exception e){
/*
Contains code to be executed if instanced of Exception is caught
*/
}
} finally { // finally block

}

try Block
The java code that you think may produce an exception is placed within a try block for a suitable catch block to handle the error.If no exception occurs the execution proceeds with the finally block else it will look for the matching catch block to handle the error. Again if the matching catch handler is not found execution proceeds with the finally block and the default exception handler throws an exception.. If an exception is generated within the try block, the remaining statements in the try block are not executed.

catch Block
Exceptions thrown during execution of the try block can be caught and handled in a catch block. On exit from a catch block, normal execution continues and the finally block is executed (Though the catch block throws an exception).

finally Block
A finally block is always executed, regardless of the cause of exit from the try block, or whether any catch block was executed. Generally finally block is used for freeing resources, cleaning up, closing connections etc. If the finally clock executes a control transfer statement such as a return or a break statement, then this control statement determines how the execution will proceed regardless of any return or control statement present in the try or catch.

Example:

public class DivideException2 {
public static void main(String[] args) {
int result = division(100,0); // Line 2
System.out.println("result : "+result);
}

public static int division(int totalSum, int totalNumber) {
int quotient = -1;
System.out.println("Computing Division.");
try{
quotient = totalSum/totalNumber;

}
catch(Exception e){
System.out.println("Exception : "+ e.getMessage());
}
finally{
if(quotient != -1){
System.out.println("Finally Block Executes");
System.out.println("Result : "+ quotient);
}else{
System.out.println("Finally Block Executes. Exception Occurred");
return quotient;
}

}
return quotient;
}
}

Output: null ( not NullPointerException)

No comments: