Monday 26 November 2012

Java Programming - Exception Handling

Java Programming - Exception Handling
Structure
5.1 Introduction
Objectives
5.2 Definition of an Exception
Self Assessment Questions
5.3 Exception Classes
Self Assessment Questions
5.4 Common Exceptions
Self Assessment Questions
5.5 Exception Handling Techniques
5.6 Summary
5.7 Terminal Questions
5.1 Introduction
Though it is the dream to every programmer to write error-free programs it is not so normally. This is because the programmer has not anticipated all possible situations that might occur while running the program. The errors might be due to situations that might occur while running the program. The errors might be due to a programming mistake, bad input data, corrupts files or problems in physical devices. It is necessary to take care about these situations. The possible remedies could be to
 Notify the user of an error.
 Save the work environment.
 Allowing exiting from the program without adversely affecting the other programs in execution.
Objectives
In this chapter, you will learn about the:
Java Programming Unit 5
Sikkim Manipal University Page No. 121
 Definition of Exception
 Exception Classes
 Exception handling techniques.
This unit aims at providing information about handling situations occurring due to error or faulty conditions. This unit explains the mechanisms available in Java to handle such situations. The error or exception handling mechanisms in Java enables programmers to write more robust and secure codes. Java enforces the programmers to specify the exceptions that might occur while executing a method.
5.2 Definition of an Exception
The term exception denotes an exceptional event. It can be defined as an abnormal event that occurs during program execution and disrupts the normal flow of instruction.
Error-handling becomes a necessity when you develop applications that need to take care of unexpected situations. The unexpected situations that may occur during program execution are:
 Running out of memory
 Resource allocation errors.
 Inability to find a file.
 Problems in network connectivity.
If an above-mentioned situation is encountered, a program may stop working. You cannot afford to have an application stop working or crashing, if the requested file is not present on the disk. Traditionally, programmers used return values of methods to detect the errors that occurred at runtime. A variable errno was used for a numeric representation of the error. When multiple errors occurred in a method, errno would have only one value-that of the last error that occurred in the method.
Java Programming Unit 5
Sikkim Manipal University Page No. 122
Java handles exceptions the object-oriented way. You can use a hierarchy of exception classes to manage runtime errors.
Self Assessment Questions
1. What is an Exception?
2. The term exception denotes an ________.
3. Java handles exceptions the ______________ way.
5.3 Exception Classes
The class at the top of the exception classes hierarchy is called Throwable. Two classes are derived from the Throwable class- Error and Exception. The Exception class is used fro the exceptional conditions that have to be trapped in a program. The Error class defines a condition that does not occur under normal circumstances. In other words, the Error class is used for catastrophic failures such as VirtualMachineError. These classes are available in the java.lang package.
Self Assessment Questions
1. What do you mean by Throwable?
2. What are the two classes that are derived from the throwable class?
3. In which packages of java, Exception classes are available?
5.4 Common Exceptions
Java has several predefined exceptions. The most common exceptions that you may encounter are described below.
 Arithmetic Exception
This exception is thrown when an exceptional arithmetic condition has occurred. For example, a division by zero generates such an exception.
 NullPointer Exception
This exception is thrown when an application attempts to use null where an object is required. An object that has not been allocated memory
Java Programming Unit 5
Sikkim Manipal University Page No. 123
holds a null value. The situations in which an exception is thrown include:
 Using an object without allocating memory for it.
 Calling the methods of a null object.
 Accessing or modifying the attributes of a null object.
 ArrayIndexOutOfBounds Exception
The exception ArrayIndexOutOfBounds Exception is thrown when an attempt is made to access an array element beyond the index of the array. For example, if you try to access the eleventh element of an array that’s has only ten elements, the exception will be thrown.
Self Assessment Questions
1. What do you mean by ArrayIndexOutOfBounds Exception?
2. What do you mean by NullPointer Exception?
5.5 Exception Handling Techniques
When an unexpected error occurs in a method, Java creates an object of the appropriate exception class. After creating the exception objects, Java passes it to the program, by an action called throwing an exception. The exception object contains information about the type of error and the state of the program when the exception occurred. You need to handle the exception using exception-handler and process the exception.
You can implement exception-handling in your program by using following keywords:
 try
 catch
 finally
Java Programming Unit 5
Sikkim Manipal University Page No. 124
The try Block
You need to guard the statements that may throw an exception in the try block. The following skeletal code illustrates the use of the try block
try
{
// statement that may cause an exception
}
The try block governs the statements that are enclosed within it and defines the scope of the exception handlers associated with it. In other words, if an exception occurs within try block, the appropriate exception-handler that is associated with the try block handles the exception. A try block must have at least one catch block that follow it immediately.
Nested try Statements
The try statement can be nested. That is, a try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement's catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception. Here is an example that uses nested try
statements:
// An example of nested try statements.
class NestTry {
public static void main(String args[ ]) {
try {
int a = args.length;
Java Programming Unit 5
Sikkim Manipal University Page No. 125
/* If no command-line args are present,
the following statement will generate
a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[ ] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
As you can see, this program nests one try block within another. The program works as follows. When you execute the program with no
Java Programming Unit 5
Sikkim Manipal University Page No. 126
command-line arguments, a divide-by zero exception is generated by the outer try block. Execution of the program by one command-line argument generates a divide-by-zero exception from within the nested try block. Since the inner block does not catch this exception, it is passed on to the outer try block, where it is handled. If you execute the program with two command-line arguments, an array boundary exception is generated from within the inner try block. Here are sample runs that illustrate each case:
C:\\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\\>java NestTry One
a = 1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\\>java NestTry One Two
a = 2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException: 42
Nesting of try statements can occur in less obvious ways when method calls are involved. For example, you can enclose a call to a method within a try block. Inside that method is another try statement. In this case, the try within the method is still nested inside the outer try block, which calls the method. Here is the previous program recoded so that the nested try block is moved inside the method nesttry( ):
/* Try statements can be implicitly nested via
calls to methods. */
class MethNestTry {
Java Programming Unit 5
Sikkim Manipal University Page No. 127
static void nesttry(int a) {
try { // nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[ ] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
}
public static void main(String args[ ]) {
try {
int a = args.length;
/* If no command-line args are present,
the following statement will generate
a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
nesttry(a);
Java Programming Unit 5
Sikkim Manipal University Page No. 128
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
The output of this program is identical to that of the preceding example.
The catch Block
You associate an exception-handler with the try block by providing one or more catch handlers immediately after try block. The following skeletal code illustrates the use of the catch block.
try
{
//statements that may cause an exception
}
catch ()
{
// error handling code
}
The catch statement takes an object of an exception class as a parameter. If an exception is thrown, the statements in the catch block are executed. The scope of the catch block is restricted to the statements in the preceding try block only.
The finally Block
When an exception is raised, the rest of the statements in the try block are ignored. Sometimes, it is necessary to process certain statements irrespective of whether an exception is raised or not. The finally block is used for this purpose.
Java Programming Unit 5
Sikkim Manipal University Page No. 129
try
{
openFile();
writeFile(); //may cause an exception
}
catch (…)
{
//process the exception
}
In the above example, the file has to be closed irrespective of whether an exception is raised or not. You can place the code to close the file in both the try and catch blocks. To avoid duplication of code, you can place the code in the finally block. The code in the finally block is executed regardless of whether an exception is thrown or not. The finally block follows the catch blocks. You have only one finally block for an exception-handler. However, it is not mandatory to have a finally block.
finally
{
closeFile ();
}
5.6 Summary
Handling Runtime Exception
The term exception denotes an exceptional event. It can be defined as a abnormal event that occurs during program execution and disrupts the normal flow of instructions. The Exception class is used for the exceptional conditions that have to be trapped in a program.
Java Programming Unit 5
Sikkim Manipal University Page No. 130
Java has several predefined exceptions. The most common exceptions that you may encounter are:
 Arithmetic Exception
 NullPointer Exception
 ArrayIndexOutOfBounds Exception
The following keywords are used for exception-handlings:
 try
 catch
 finally
If an exception occurs within the try block, the appropriate exception-handler that it associated with the try block handles the exception.
You associate an exception-handler with the try block by providing one or more catch handlers immediately after the try block.
Sometimes, it is necessary to process certain statements, no matter whether an exception is raised or not. The finally block is used for this purpose.
5.7 Terminal Questions
1. What is the difference between errors and exceptions?
2. Why runtime exceptions need not be caught or specified?
3. Give 3 examples for runtime exception?
4. Write a program to copy one file to another file?
5. What are the different types of Exception?
6. What are the different Exception handling techniques?

No comments:

Post a Comment