Contents
Aim
To write a program for demonstrating exception handling using Java.
Theory
Exception
An abnormal condition that occurs at run-time or a run-time error is known as an exception.
Exception Handling
Handling exceptions is known as exception handling. Instead of letting the program crash (terminate abnormally) when an error occurs at run-time, we provide meaningful error messages to the users by handling the exception(s).
Java aids exception handling by providing five keywords: try, catch, throw, throws, and finally. Their use is described as follows:
- try: Statements that are supposed to raise exception(s) are placed inside a try block.
- catch: Code that handles exceptions are placed in catch blocks. A try block must be followed by one or more catch blocks or a single finally block.
- throw: Most of the exceptions are thrown automatically by the Java run-time system. We can throw exceptions manually using throw keyword.
- throws: If a method which raises exceptions doesn’t want to handle them, they can be thrown to parent method or the Java run-time using the throws keyword.
- finally: All the statements that should execute irrespective of whether a exception arises or not is placed in the finally block.
The general form of an exception handling block looks as follows:
try
{
//Statements that might arise exceptions
}
catch(ExceptionType1 obj)
{
//Exception handling code
}
catch(ExceptionType2 obj)
{
//Exception handling code
}
...
finally
{
//Code that execute even if exception(s) occur or not
}
Exception Handling Example
Let’s see a sample Java program which handles “divide by zero” exception. First let’s see the Java program without using exception handling constructs. The program is given below:
class Divide
{
public static void main(String[] args)
{
int a = 10, b = 0;
int c = a / b;
System.out.println("Result is: " + c);
}
}
The output of the above program is:
Exception in thread “main” java.lang.ArithmeticException: / by zero
at Divide.main(Divide.java:6)
The above output says that the exception was raised in main method, exception raised was ArithmeticException and the associated message is / by zero, exception was raised in Divide class, in Divide.java file and on line number 6.
Now, let’s use exception handling constructs to provide our own exception handling code (message). The program is given below:
class Divide
{
public static void main(String[] args)
{
try
{
int a = 10, b = 0;
int c = a / b;
System.out.println("Result is: " + c);
}
catch(ArithmeticException e)
{
System.out.println("b cannot be zero");
}
}
}
Pseudo code / Steps
- Create a class
- Create a method which takes two parameters x and y and prints the result of x/y. Use exception handling to handle divide by zero and print the message “Second value cannot be zero” when y is given the value zero.
- Create a method which takes an integer as a parameter. The method uses the given integer as an index and prints the value available at that index in the array. Use exception handling and print a message “Invalid index” when user supplies an index out of range for the array.
- Create a Driver class, create an object for the other class.
- Call the methods with appropriate values.
Program
import java.util.Scanner;
class ExceptionDemo
{
void divide(int x, int y)
{
try
{
System.out.println("Result = " + (x/y));
}
catch(ArithmeticException e)
{
System.out.println("Second value cannot be zero");
}
}
void showitem(int i)
{
int a[] = {1,2,3,4,5};
try
{
System.out.println("Value at given index is " + a[i]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Invalid index");
}
}
}
class Driver
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter two numbers");
int x = s.nextInt();
int y = s.nextInt();
ExceptionDemo obj = new ExceptionDemo();
obj.divide(x,y);
System.out.println("Enter the index value");
int i = s.nextInt();
obj.showitem(i);
}
}
Input and Output:
Run1:
Enter two numbers
10
5
Result = 2
Enter the index value
4
Value at given index is 5
Run2:
Enter two numbers
10
0
Second value cannot be zero
Enter the index value
7
Invalid index
Result
The concepts related to exception handling has been understood and implemented successfully.

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Leave a Reply