Home > Articles

Java Performance: Using Exceptions as Intended

  • Print
  • + Share This
Virendra Mehta explains that, while exceptions are a useful facility in Java, allowing us to handle errors and other unusual circumstances in an appropriate manner, they also have limitations that we must take into consideration.
Like this article? We recommend

Exceptions in Java

Exceptions are an important part of most object-oriented languages, including the two most common languages today—C++ and Java. They provide a good way of handling errors and other exceptional situations, allowing the program to recover from an unusual incident and continue, or to quit gracefully. Java makes it especially easy by allowing an exception to be represented by an object—possibly sub-classed from the Exception class—and thus exceptions are used very widely in Java programming.

Listing 1 shows different ways of using exceptions:

Listing 1

import java.lang.*;
public class DivNumbers {
   public static void testMe(int x, int y) throws Exception {
      if (y == 0)
         throw new Exception("Dividing by zero");
   public static void main(String args[]) {
      try {
         int x = Integer.parseInt(args[0]);
         int y = Integer.parseInt(args[1]);

         testMe(x, y);
         System.out.println("The result is " + x/y);
      } catch (ArrayIndexOutOfBoundsException arrEx) {
           "Usage: java DivNumbers numerator denominator");
      } catch (Exception e) {
      } finally {
         System.out.println("Thank you for using me");

This example shows the implementation of a class that returns the result of division of two numbers passed on the command line. The main method invokes a private method that checks whether the denominator is zero. If so, it throws an instance of the Exception object. If the denominator is nonzero, testMe should return quietly and main should print the output of the division. Otherwise, Exception is thrown and caught by the catch clause, which uses the general case of Exception, and an error message is printed. Another interesting case is that while reading the numbers to be divided, if the user doesn't pass at least two numbers, we could run into an out-of-bounds exception while accessing args. This prompts a Usage message. Finally, the finally clause ensures that whatever we do, we would execute the "thank you" message.

  • + Share This
  • 🔖 Save To Your Account