Exception Handling in Java - the Basic Concepts


The Exceptions are runtime errors wich may be frustrating to your end use if not handled by the program. Java provide an excellent way to take care of the runtime errors, this post is first part of two part exception handling series. This will teach you basics with what is caught and uncaught exceptions.

Introduction

The errors are always a frustration for a programmer, but they becomes serious damage for any programmer or software vendor if some bug is out there are client side. As Java is strongly typed language so it is capable to prevent the bugs passing through the compiler but there are some other type of errors which may come at runtime. Instead of classifying these runtime errors as error, Java classifies these as exceptions.

The Idea behind Exceptions

The Idea behind the Exceptions comes from the runtime anomalies which may effect the program and sometimes these could be so fatal that, it may halt the program execution. For example if you are taking the input at runtime and storing it in the variables and later at some point you want to divide these two. For compiler it is fine to divide two variables as it is legal. But User may enter the value 0 in the denominator and as the division by 0 is illegal so this would halt the functioning of program.

But Java provides a solution, which is known as exception handling. By using exception handling you may give an alternative to JVM in case above case occurs.

Types Of Exception

In Java there are two branches of error. as shown in following branching

Errors in Java
|_Error
|	
|_Exception
	|_checked(caught)[examples: ClassNotFoundException, InterruptedException, IllegalAccessException]
	|
	|_unchecked(uncaught)[examples: NullPointerException, NumberFormatException, SecurityException]

The meaning is simple. There are two type of Errors where there is exact error or else there is some runtime problem. Checked Exceptions are those which are not let away by compiler for example the fileNotFound Exception. If you are doing some file handling compiler will tell you to use exception handling however for the unchecked exception type the compile would not warn you for the occurrence of exception for example the ArrayIndexOutOfBoundException.

Handling Exception

If you understand the basic concept of exception handling and want to move on to some programming it is the time to introduce you with a few new keywords.
try, catch, throw, throws, finally are the main keywords you are going to use now.

let us see a very basic example in two versions


public class ExceptionDemo {
    public static void main(String[] args){
        int[] a = new int[5];
        System.out.println(a[10]);
    }
}

if you try to run this program this will result in following error message

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
	at ExceptionDemo.main(ExceptionDemo.java:4)
Java Result: 1

As you can see from the message the program tried to access the array index 10 which is not present, as the array in only 5 element array. let us now modify this program to include the exception handling.


public class ExceptionDemo {
    public static void main(String[] args){
        int[] a = new int[5];
	try{
	        System.out.println(a[10]);
		System.out.println("After Exception");
	}
	catch(Exception e){
		System.out.println("Exception caught+"e);
	}
	System.out.println("After try/catch");
    }
}

the output will be as follows:

Exception caught:java.lang.ArrayIndexOutOfBoundsException: 10
After try/catch

as you can now see the system when encounter the exception statement this will break the program and throw the exception, which will be caught by nearest catch block.

Note that it is usually best to use the lower classes from exception hierarchy but if you don't know which type of exception will occur it is good to use Exception class as it is super class for most of the Exception classes and is at a high position in exception hierarchy. After executing code from the catch block the control will be transferred to the statement just after the catch block.

There is more to it, the finally block. The finally block is executed in any case weather or not the exception encounter. Try these two variations of program and check the output.


/*
without any exception occurring
*/
public class ExceptionDemo {
    public static void main(String[] args){
        int[] a = new int[5];
        try{
           System.out.println(100/10);
           System.out.println("After Divide statement");
        }
        catch(Exception e){
            System.out.println("Exception caught:"+e);
        }
        finally{
            System.out.println("In finally block");
        }
        System.out.println("After try/catch");
    }
}

output is as follows:

10
After Divide statement
In finally block
After try/catch

/*
and now with the exception occurring
*/
public class ExceptionDemo {
    public static void main(String[] args){
        int[] a = new int[5];
        try{
           System.out.println(100/0);
           System.out.println("After Divide statement");
        }
        catch(Exception e){
            System.out.println("Exception caught:"+e);
        }
        finally{
            System.out.println("In finally block");
        }
        System.out.println("After try/catch");
    }
}

the output is as follows:

Exception caught:java.lang.ArithmeticException: / by zero
In finally block
After try/catch

So I hope now you understand the try catch and finally. There is more to the concept of Exception handling which is explained in the next part of this post.

Exception Handling part 2 - Advance Concept