/* related posts with thumb nails */

program to demonstrate Exception handling:

Example: The following program demonstrates exception handling. If zero is supplied for the second argument through command line, the code attempts to divide the first value with zero which raises a runtime error. But, as we have used exception handling mechanism here with appropriate catch block, the exception will be caught and the program will not be abruptly terminated.

class Test


public static void main(String as[])


int a=Integer.parseInt(as[0]);

int b=Integer.parseInt(as[1]);



System.out.println(“Division=”+ (a/b));


catch(ArithmeticException e)


System.out.println("Please check the Denominator”);





Exception Handling:

Exception Handling: Handling runtime errors is exception handling. In java, when an abnormal condition occurs within a method then the exceptions are thrown in form of Exception Object i.e. the normal program control flow is stopped and an exception object is created to handle that exceptional condition. If the exception object is not caught and handled properly, the interpreter will display an error message and it will terminate the program. If we want the program to continue with the execution of the remaining code, then we should try to catch the exception.

The purpose of exception handling mechanism is to provide a means to detect and report an "exceptional circumstance" so that appropriate action can be taken. The mechanism performs the following tasks:

1. Find the problem.

2. Inform that an error has occurred (Throw the exception)

3. Receive the error information (Catch the exception)

4. Take corrective actions (Handle the exception)

The error handling code basically consists of two segments, one to detect errors and to throw exceptions and the other to catch exceptions and to take appropriate actions. Exception handling mechanism includes the key words: try, catch, throw, throws and finally.

The above program produces the following output.

Output 1: (No Exception)

D:\java>java Test 6 2
Division =3

Output 2: (With Exception)

D:\java>java Test 6 0
Please check the Denominator

Related Topics:


Post a Comment