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 acatch
clause or by forwarding it outward with thethrows
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
-
Exceptions due to programming errors: In this category, exceptions are generated due to programming errors (e.g.,
NullPointerException
andIllegalArgumentException
). 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
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
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:
/*
Contains code to be tested
*/
}catch(Exception e){
/*
Contains code to be executed if instanced of Exception is caught
*/
}
} finally { // finally 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
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:
Post a Comment