These tutorials will introduce you to Java programming Language. You'll compile and run your own Java application, using Sun's JDK. It's extremely easy to learn java programming skills, and in these parts, you'll learn how to write, compile, and run Java applications. Before you can develop corejava applications, you'll need to download the Java Development Kit (JDK).


PART-5


Catching Exceptions

An exception is a point in the code where something out of the ordinary has happened and the regular flow of the program needs to be interrupted; an exception is not necessarily an error. A method which has run into such a case will throw an exception using the throw(ExceptionClass) method. When an exception is thrown it must be caught by a catch statement that should sit right after a try statement.

// This is the Hello program in Java
class Hello {

    public static void main (String args[]) {
    
      /* Now let's say hello */
      System.out.print("Hello ");
      System.out.println(args[0]);
  }

}

If you run the program without giving it any command line arguments, then the  runtime system generates an exception something like,

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at Hello.main(C:\javahtml\Hello.java:7)

Since we didn't give Hello any command line arguments there wasn't anything in args[0]. Therefore Java kicked back this not too friendly error message about an "ArrayIndexOutOfBoundsException."

we can fix this problem by testing the length of the array before we try to access its first element (using array.length). This works well in this simple case, but this is far from the only such potential problem. 

What is an Exception ?

Let us see what happens when an exception occurs and is not handled properly

When you compile and run the following program

public class Test{ 
    public static void main(String str[]){
    int y = 0;
    int x = 1;
    // a division by 0 occurs here.
    int z = x/y;
    System.out.println("after didvision");
  }
}

The execution of the Test stops and this is caused by the division by zero at - x/y - an exception has been thrown but has not been handled properly.

How to handle an Exception ?

To handle an Exception, enclose the code that is likely to throw an exception in a try block and follow it immediately by a catch clause as follows

public class Test{ 
    public static void main(String str[]){
        int y = 0;
        int x = 1;
        // try block to "SEE" if an exception occurs
        try{
          int z = x/y;
          System.out.println("after didvision");
           // catch clause below handles the 
          // ArithmeticException generated by 
          // the division by zero.
       } catch (ArithmeticException ae) 
       {System.out.println(" attempt to divide by 0");}
       System.out.println(" after catch ");
   } 
}

The output of the above program is as follows

attempt to divide by 0 
after catch

the statement - System.out.println("after didvision") - is NOT executed, once an exception is thrown, the program control moves out of the try block into the catch block.

The goal of exception handling is to be able to define the regular flow of the program in part of the code without worrying about all the special cases. Then, in a separate block of code, you cover the exceptional cases. This produces more legible code since you don't need to interrupt the flow of the algorithm to check and respond to every possible strange condition. The runtime environment is responsible for moving from the regular program flow to the exception handlers when an exceptional condition arises.

In practice what you do is write blocks of code that may generate exceptions inside try-catch blocks. You try the statements that generate the exceptions. Within your try block you are free to act as if nothing has or can go wrong. Then, within one or more catch blocks, you write the program logic that deals with all the special cases.

To start a section of code which might fail or not follow through you start a try clause:

try
{
  // Section of code which might fail
}

The try statement is needed in case of an exception. If the read fails in some way it will throw an exception of type java.io.IOException. That exception must be caught in this method, or the method can declare that it will continue throwing that message. Exception handling is a very powerful tool, you can use it to catch and throw exceptions and thus group all your error handling code very well and make it much more readable in larger more complex applications. After the try section there must exist one or more catch statements to catch some or all of the exceptions that can happen within the try block. Exceptions that are not caught will be passed up to the next level, such as the function that called the one which threw the exception, and so on. .

try
{
  // Section of code which might fail
}
catch (Exception1ThatCanHappen E)
{
  // things to do if this exception was thrown..
}
catch (Exception2ThatCanHappen E)
{
  // things to do if this exception was thrown..
}

Here's an example of exception handling in Java using the Hello World program above:

Source Code

// This is the Hello program in Java
class ExceptionalHello {

    public static void main (String args[]) {
    
      /* Now let's say hello */
      try {
        System.out.println("Hello " + args[0]);
      }
      catch (Exception e) {
        System.out.println("Hello whoever you are");      
      }
  }

}

You may or may not print an error message. If you write an exception handler and you don't expect it to be called, then by all means put a

System.out.println("Error: " + e);

This has the folowing advantages over handling your errors internally:

  • You can react to an error in custom defined way. A read error does not mean that the program should crash.
  • You can write code with no worry about failure which will be handled by the users of your class.
  • You can group your error handling code much better.
  • You can make your application more transactional focused with nested try catch blocks:

A simple Java code which demonstrates the exception handling in Java

Refer to the java API document to see all exception types that can be handled in Java.

Source Code

public class excep2
{
	public static void main(String args[])
	{
		int i =0 ;
		//Declare an array of strings
		String Box [] = {"Book", "Pen", "Pencil"};
		while(i<4)
		{
			try
			{
				System.out.println(Box[i]);
				
			}
			catch(ArrayIndexOutOfBoundsException e)
			{
				System.out.println("Subscript Problem " + e);
			i++;
			}
			finally
			{
				System.out.println("This is always printed.");
			}
			i++;
		}
	}
}