Thursday, 29 August 2013

Exceptions in Java - Detailed Explanation



Exception == “Exceptional Event”

What is an Exception?

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions.

What happen when an error occurs in the program?


The method in which the error occurs will create an object called exception object and provide it to the runtime system.

The exception object contains information about the error, including its type and the state of the program when the error occurred.

Creating an exception object and providing it to the runtime system is called throwing an exception.

“The exception must be handled in order to successful execution of the program.”

The Call Stack in Java +Maven Scientists 

To handle the exception, the runtime system will search the call stack for a method which contains a block of code that can handle the exception. We call this block of code an exception handler.

The searching of call stack begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called.

When an appropriate handler is found, the runtime system passes the exception to the handler. Appropriate Handler is one that has the same type as of the exception object.

If the appropriate handler is not found by searching in the call stack, then the program will terminate with an error.

Kinds of Exception

There are 3 kinds of exceptions. Checked, Error and Runtime Exceptions

1. Checked Exception – 

A well written code should catch this kind of exception at the compile time. Appropriate exception handlers should be included into the application code.

Example: The application is trying to open a file which does not exist or has been deleted. An exception named java.io.FileNotFoundException will be thrown. A well written application will catch this error and notify the user about this.

2. Error – 

Error is an exceptional case and is due to an external source, not from the application itself. Generally, the application cannot recover from this.
Example: An application successfully opens a file for input operation. But, due to a system malfunction, the write operation became unsuccessful. This will throw java.io.IOError exception. An application might catch this exception, in order to notify the user of the problem — but it also might make sense for the program to print a stack trace and exit.

3. Runtime Exception – 

A runtime exception is also an exceptional case but is internal to the application. The application cannot recover from this kind of exception. This indicates bad programming practices and highlights bugs in the code. We may also call them as logical errors.

Example: While trying to access an element in the 7th index in an array. But, the size of the array is 6 thus, causing the runtime to throw java.lang.ArrayIndexOutOfBoundsException

Similarly, NullPointerException is also a type of Runtime Exception

The try Block


The code that might give an exception is written into the try block. This is the first step in providing an exception handler to the code.
If an exception occurs in the try block, then the exception is handled by an exception handler associated with it.

The catch block follows the try block in order to provide an exception handler.

Syntax:


try {
// code that might give an exception
}
catch and finally block..

The catch Block


The catch block associates the exception handler with the try block. The catch block comes just after the try block ends. Note that the catch block comes directly after the try block and no code can be written between them.

You can provide multiple catch blocks with a single try block.

Code Example:

try {

} catch (TypeOfException name) {

} catch (TypeOfException name) {

}

Each catch block is an exception handler and handles the type of exception which is indicated by its argument. The argument type – TypeOfException declares the type of exception that can be handled by the handler. The name is through which we can refer to the exception object.

The code contained in the catch bock is executed if and only if an exception has occurred in the try block.
 

Code Example:

 
try {
 
} catch (FileNotFoundException e) {
    System.err.println("Caught FileNotFoundException: " + e.getMessage());
 
} catch (IOException e) {
    System.err.println("Caught IOException: " + e.getMessage());
}


You can catch more than one exception with a single catch block:



This feature is available only in Java SE 7 and above versions. This reduces duplicity of code.

Code Example:

 
catch (IOException | NullPointerException ex) {
    System.out.println(“Exception : ” + ex.getMessage() );
}

Note: If a single catch handler handles more than one exception, then the name ex is automatically final. Which means you cannot assign any values to it within the catch block.

The finally Block


The finally block will always execute when the try block exits. The finally block executes despite the occurrence of an unexpected exception. The finally block acts as the savior in unexpected situations and is quite advantageous to the programmer and application user.

Example: An application successfully opens a file for input operation. But, due to a system malfunction, the write operation became unsuccessful. This will throw java.io.IOError exception. Even if the exception is handled, the file input stream is not closed because the code to close the file input stream has not executed. So, the code to close the file input stream should be written in the finally block to prevent data corruption of file.

Note: If the JVM exits while the execution of the try or catch block, the finally block may not execute. Or, if the thread executing the try or catch block is killed or interrupted, the finally block may not execute.

Code Example:

 
PrintWriter out = null;
 
try {
    System.out.println("Inside try statement");
    out = new PrintWriter(new FileWriter("File.txt"));
    for (int I = 0; I < 10; I++) {
        out.println(I);
    }
}
catch (IOException | NullPointerException ex) {
    System.out.println(“Exception : ” + ex.getMessage() );
}
finally {
    if (out != null) { 
        System.out.println("Closing PrintWriter");
        out.close(); 
    } else { 
        System.out.println("PrintWriter not open");
    } 
} 
 

Get Ebooks delivered to your email id

Comments

Subscribe to our channel

Facebook

Powered by Blogger.

Home | Contact Us | DMCA | Terms of Service | Privacy | Advertise

Maven Scientists