AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1364&pId=-1
Exception Handling in Java
page
by Debjani Mallick
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 27010/ 33

Introduction

Exception is an event occurrence which disrupts the normal flow of execution of instructions in a program. Java uses this to handle errors and other exceptional events.

When an error occurs in a method, an object (exception object) is created by the method which is handed over to the runtime system. This process is called throwing an exception. The object contains the details of the error, its type, etc. The runtime system after receiving the exception tries to find an appropriate way to handle it. The runtime method searches the call stack to find an appropriate method containing the code for handling the exception. That block of code is called exception handler.

When the type of exception thrown by the runtime system matches with the type of exception that can be handled by an exception handler in a method, then the exception is passed on to the handler so that it can catch the exception. If the runtime system does find any appropriate handler for the exception, the runtime system and consequently the program terminates. Normally we have three types of exceptions: checked exceptions, errors and runtime exceptions.

Classes

Throwable is a class of Java.lang package which is considered as the superclass of all errors and exceptions in the Java language. It should be kept in mind that only objects that are instances of this class or its subclasses are thrown by the Java Virtual Machine (JVM) or can be thrown by the Java throw statement. Similarly, only this class or its subclasses can be the argument for the catch statement.

The two main subclasses of Throwable class are as follows.

·         Error

·         Exception

Errors are thrown by the virtual machine when there is a dynamic linking failure or any other hardware failure. Errors are not normally thrown by a simple program. Normally programs catch and throw exception derived for Exception class.

Exception class is again subdivided into two subclasses:

·         IOException

·         RunTimeException

IOExceptions are mainly caused by failed or interrupted input or output operations. These are mainly of two types:

·         EOFException – This exception is caused when the end of the file or end of the stream is encountered unexpectedly during input.

·         FileNotFoundException - This exception is caused when a file in a specified path is not found.

RunTimeExceptions are exceptions that are caused due to some programming problem that was detected by the runtime device or an inappropriate use of the application programming interface. These can occur anywhere in a program. They include:

·         ArithmeticException – This exception occurs when there is some error in the arithmetic logic- if we have some exception in the arithmetic condition. An example of this type of exception is trying to divide a number by zero.

·         NullPointerException – This exception occurs when an application tries to use null where an object should have been used.

IndexOutOfBoundException – This exception occurs when an index of some sort is out of range. It can be of type:

·         ArrayIndexOutOfBoundException

·         StringIndexOutOfBoundException

The various keywords for handling exceptions are below.

·         try

·         catch

·         finally

·         throw

·         throws

Using try, catch and finally

The syntax for the usage of try, catch and finally block is given below.

Listing 1

try
{
      ………
      ………
}
catch(exceptionclass obj1)
{
      ………
      ………
}
catch(exceptionclass obj2)
{
      ………
      ………
}
finally
{
      ………
      ………
}

For using an exception handler in an application, the first step we need to do is to enclose the code that is likely to generate an exception inside a try block. If an exception occurs in the try block then it is handled by the exception handler associated with it. For associating an exception handler to the try block, we need to have one or more catch blocks after the try block where each catch block acts as an exception handler and can handle the type of exception indicated by its arguments. Exception handlers can be used to print an error message when an exception occurs, to halt the program, to redirect the error to a higher level handler using chained exception, to write code for recovering from the error, etc. The finally block is the block which is always executed when the try block exits which ensures that the finally block is executed even when an unexpected exception occurs. It acts as the appropriate place for writing the clean up code.

Listing 2

class exceptionDemo
{
  Random r = new Random();
  int a = r.nextInt();
  int b = r.nextInt();
  int c = r.nextInt();
  try
  {
    c = a / b / c;
    System.out.println("Value of c " + c);
  }
  catch (ArimeticException e)
  {
    System.out.println("The error is " + e);
  }
}
Using throw and throws

The syntax for the usage of throw and throws clause is given below.

Listing 3

public void functionname throws exceptionclass
{
      ………
      ………
throw
      ………
      ………
}

Before catching an exception, some code should throw the exception first. An exception can be thrown by the code of the program, Java runtime environment, etc. One can use the exceptions defined in Throwable class or he can also create exceptions of his own.

Listing 4

class myException extends Exception
{
  int age;
  myException(int x)
  {
    age = x;
  }
  String toString()
  {
    return ("Age below requirement(" + age + ")");
  }
}
 
class exec
{
  public void vote(int x)throws myException
  {
    System.out.println("Voting condition ");
    if (x < 18)
      throw new myException(x);
    System.out.println("You are eligible to vote ");
  }
}
class demo
{
  public static void main(String a[])
  {
    exec obj = new exec();
    try
    {
      obj.vote(21);
      obj.vote(15);
      catch (myException e)
      {
        System.out.println("Error occured " + e);
      }
    }
  }

In the above example, toString() has been used. ToString() and getMessage() are the methods of every exception class. For the above program, an error occurs where we have passed 15 as the age, but for 21 the program executes successfully.

Conclusion

Using exceptions in a program provides us with various advantages.

In traditional style of programming, detection and handling of an error results in a disorganized code, whereas exception give us the advantage of separating the normal flow of program logic from the code that handles when something abnormal happens.

Exceptions give us the scope of organizing and differentiating between different error types using a separate block of codes.

One of the significant features which exception provides is the ability to propagate the error reporting up the call stack of methods.

By Debjani Mallick


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-28 11:25:43 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search