Tuesday, November 15, 2011

Tutorial: Java Exception Handling Using Try and Catch


by eturo

Introduction
An exception is an error that occurs at run time. Using Java’s exception handling subsystem you can, in a structured and controlled manner, handle run-time errors. Although most modern programming languages offer some form of exception handling, Java’s support for it is cleaner and more flexible than most others.

Advantages:

ü  it automates much of the error handling code that previously had to be entered “by hand” into any large program
o    For example, in some computer languages, error codes are returned when a method fails, and these values must be checked manually, each time the method is called. This approach is both tedious and error-prone.
ü  it allows your program to define a block of code, called an exception handler, which is executed automatically when an error occurs
o    It is not necessary to manually check the success or failure of each specific operation or method call. If an error occurs, it will be processed by the exception handler.
ü  it defines standard exceptions for common program errors, such as divide-by-zero or file-not-found
o    To respond to these errors, your program must watch for and handle these exceptions. Also, Java’s API library makes extensive use of exceptions.

¤  The Exception Hierarchy
      in Java, all exceptions are represented by classes
      all exception classes are derived from a class called Throwable
Ø  there are two direct subclasses of Throwable: Exception and Error
§  Error subclass these are errors that occur in the Java virtual machine itself, and not in your program.
§  Exception subclass – these are errors that result from program activity
·         an important subclass of Exception is RuntimeException, which is used to represent various common types of run-time errors

¤  Exception Handling Fundamentals
      Java exception is unexpected event that happens in the system
      Java exception handling is managed via five keywords: try, catch, throw, throws, and finally
Ø  program statements that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown
Ø  your code can catch this exception using catch and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system.
Ø  to manually throw an exception, use the keyword throw. In some cases, an exception that is thrown out of a method must be specified as such by a throws clause.
Ø  any code that absolutely must be executed upon exiting from a try block is put in a finally block

A.      Try and Catch
      you can’t have a try without a catch, or a catch without a try.
      general form of the try/catch exception handling blocks:

                  try {
                      // potential risky code
                  }
                  catch( Exception object) {
                      // how to solve the exception
                      // cannot solve it, throw an exception
                                         }


Note: If no exception is thrown, then a try block ends normally, and all of its catch statements are bypassed. Execution resumes with the first statement following the last catch. Thus, catch statements are executed only if an exception is thrown.





Example 1:
Suppose we are working a program that deals about arrays in Java. The program below actually does not contain syntax errors when you compile it, but when executing or running the program, it triggers a run-time error known as ArrayIndexOutOfBoundsException. As we can we see, the program does not have any Java exception that handles the said error. Here is the original code without an exception-handler:

public class ExceptionDemo
{
public static void main(String[] args)
{
            int nums[] = new int[4];

nums[4] = 10;
            System.out.println("The value is " + nums[4]);
      }
}

When you run this program using the BlueJ text editor, this will display the run-time error message (see image below):


 

Why this error occurred? It is because the declared size of the array is 4, so it means that the last index of the array is 3 (last index = array size – 1). As we can see in the program, we attempt to assigned value 10 into our array at index 4 (indicated by the highlighted yellow line) which is out of bounds to the size of our array or our array does not contain a memory location of value 10 for index 4. So then, during the execution or run-time of our program, the JVM throws an ArrayIndexOutOfBoundsException error and it causes an efficient termination of our program. Now, in Java we can prevent this run-time error by using an exception/error handler using the try and catch.

Here is the implementation of try and catch:

public class ExceptionDemo {
    public static void main(String args[])
    {
        //creates an array that can contains 4 integer numbers
        int nums[] = new int[4];
           
        //if there is no error occurred here then the statements inside will be executed
        try {
            System.out.println("Before exception or error is occurred.");
            //this generates an index out-of-bounds exception.
            //assigned value 10 to index 4 of the array which is out-of-bound to its size
            nums[4] = 10;
            //this will not be printed or executed if some errors occur
            System.out.println("The value is " + nums[4]);
        }
        //if there is an error occured in the try statement
        //then that exception/error will be thrown and catch in this section
        catch (ArrayIndexOutOfBoundsException exc)
        {
            // catch the exception throws by "try"
            // the printed statements in the "try" will be printed
            // you can create error message here related to the exception thrown
            System.out.println("\nWarning! Exception or error occured.");
            System.out.println("Error Message: Array index is out-of-bounds!");
        }
        System.out.println();
        System.out.println("This will print after catch statement.");
    }
}

The Output:

         

Like Us on Facebook

Related Posts Plugin for WordPress, Blogger...