by Dinesh Thakur Category: Exception Handling

An exception is an abnormal condition occurring during the execution of a program that causes it to deviate from the normal execution path. When an exception occurs, it makes further execution of the program impossible. An exception can be defined as      follows:

An exception is an event that may cause abnormal termination of the program during its execution.

Different types of error-user errors, logic errors or system errors-can cause exceptions.

Examples of errors include division by zero, out of array bounds, running out of virtual memory, opening an invalid file for reading and trying to read from an empty stack.

Whenever an error occurs during the execution of a program, it throws an exception. If the exception is not handled properly, the program execution is abruptly terminated, causing serious problems. In some books, the phrase 'throws an exception' is also sometimes replaced by 'raises an exception' or 'triggers an exception'.

Run-time error management in programming languages is a challenging task. In traditional programming languages such as C, Pascal and FORTRAN, common errors are handled by providing if-else statements. Detection of errors and handling them is often confusing, tedious and time consuming. On other hand, object oriented programming languages such as C++ and Java treat errors (or error conditions) as objects and provide exception handlers that are separate from the basic code so that the errors can be tackled efficiently.

What is involved in handling exceptions? Exception handling is a mechanism that enables programs to detect and handle errors before they occur rather than allowing them to occur and suffering the consequences. It is designed for dealing with synchronous errors such as an attempt to divide by zero.

The need for error handling can be better understood by studying Program and analyzing the outputs corresponding to different inputs.

Program a common exception: dividing by zero.

Public class Divide


    Public static void main (String [ ] args)


       System.out.println ("\n Program starts here\n");

       int a, b, c;

       a = Integer.parselnt (args [0]);

       b = Integer.parselnt (args [1]);

       c = a/b;

       System.out.println (c + "=" + a +"/"+b);

       System.out.println ("\n Program Ends here");



Program shows the following outputs for two different sets of input:

C\javatest>java Divide 4 2

Program starts here

2 = 4/2

Program Ends here

C\javatest>java Divide 4

Program starts here

Exception in thread "main"


at Divide.main ( 0)

C:\javatest>java Divide a 4

Program starts here

Exception in thread "main" java.lang.NumberFormatException: a

at java.lang.lnteger.parseInt (

at java.lang.lnteger.parseInt (

at Divide.main (

C:\javatest>java Divide 4 0

Program starts here

Exception in thread "main" java.lang.ArithmeticException:/ by zero at Divide.main (


The program will be executed successfully (as in the case of the first run, that is, java Divide 4 2) if two conditions are met:

1. If number of arguments passed at run-time are two

2. If the arguments passed are both valid numbers

A run-time error occurs if any of the following takes place:

1. If the number of arguments passed is less than two (more precisely, not equal to two)

2. If any of the arguments passed is not a number

3. If the second argument is zero

So when the program terminates abnormally, the last statement,

println ("Program Ends here") is never executed.

To prevent interruptions of the normal flow of a program from exceptions, such as the ones discussed above, exception handlers in the program identify the exceptions and handle them appropriately. Exception handlers provide applications with many benefits, more than the traditional error-handling mechanisms. If there is no user-provided exception handler, the Java run-time system provides a default mechanism to terminate the program.

What is an exception handler? An exception handler is a piece of code used to deal with the exceptions, either to fix the error or abort execution in a sophisticated way. It is invoked when an exception is encountered.          Exception handlers catch the exceptions raised during the execution of the code and handle them according to the instructions given in the handler code. In Java, exception handlers are represented as catch blocks.

The catch block in Java is used to handle exceptions that are raised during program execution.

Basics of Exception Handling in Java

The strong capability of Java to handle exceptions makes it possible for the programmer to monitor the program for exceptional conditions within it and transfer control during such conditions to a special exception-handling code that he or she provides along with the main code.

Java's exception-handling mechanism is geared to situations in which the method that detects an error is unable to deal with it. Such a method will throw an exception. There is no guarantee that there will be an 'Exception Handler' that is specifically designed to process that particular exception. If there is, the exception will be caught and handled.

A catch block contains Java code to handle exceptions so that the program will not terminate abnormally. Look at the following code:

Public static float Divide (float a, float b)


   float c;



    c = a/b;


   catch (Arithmetic' Exception e)


     System.out.println ("The exception is" +e);



In the above method, divide (), when the statement in the try block attempts to divide by zero (by passing zero value for b), the exception ArithmeticException will be raised. Immediately, the catch block catches this exception and handles it. The catch block displays the string in the println () method.

When an exception occurs, as described in the previous paragraph, Java creates an exception object and performs an action called 'throwing an exception'. The run-time system searches through the catch block, which is a block of code that is designed to handle the exception. It searches, starting from the method in which the exception occurred and searches backwards up to the call stack. This search continues till the run-time system finds a method that contains an appropriate exception handler. An exception handler is said to be appropriate if the type of the

exception thrown is the same as the type of exception that can be dealt with by the handler or one of its sub-classes. The way to handle an exception is first to look for an appropriate handler associated with the block that has been thrown. If there is no appropriate handler, within that block the search progresses up through the call stack until an appropriate handler is found which can handle the exception. If no appropriate exception handler is found, the run-time system stops and the program terminates.

Once an exception is thrown, the block in which the exception is thrown expires and control cannot return to the throw point.

That is, it is an unconditional transfer of control. Thus Java uses the termination model of

exception handling rather than the resumption model. In the resumption model, control would return to the point at which the exception was thrown and the program would resume execution. (This is similar to a function call.)

When an exception occurs, it is possible to communicate information to the exception handler from the vicinity of the location of the exception. The exception object generally contains

Information about the exception, such as its type and the state of the program when the exception occurred. The three important features that an exception usually carries are the following:

1. The type of exception-determined by the class of the exception object.

2. Where the exception occurred-the stack trace.

3. Context information-the error message and other state information.

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.