ArithmeticException Handling Java Example


Introduction

Generally, a fresher learning a programming language like C-lang, thinks that when his program is compiled, the output is guaranteed. With a bit of more practice, he comes to know that there may be problems raised by the system that prevents the program execution. These problems raised at runtime by the system (in Java, JVM) are known as exceptions.

Exceptions come into picture, after the program gets compiled successfully. Compiler gives guarantee of syntax but not output or execution.

When a runtime problem, known as exception, arises in the code, the program terminates from the point of problem occurrence, but earlier code is executed and output is given.

If the exception raised is handled or caught or trapped by the Programmer successfully, the execution goes further to the end by keeping pending the execution of problematic code.

What is ArithmeticException?

In an arithmetic operation, if the divisor (denominator) is 0, it is undefined. If the user is asked from keyboard at runtime, to enter cost of mangoes and number of mangoes, cost is entered as 500 and number as 0 by mistake, here, JVM is unable to evaluate the result and thereby terminates the execution. Before terminating, because Java is developed as a friendly language, it gives a message of the problem.

Every runtime problem, in Java, is represented by a class. For example, the earlier division by zero problem is represented by a class called ArithmeticException (from java.lang package). Similarly, accessing an array element beyond the size of the array is represented by a class called ArrayIndexOutOfBoundsException (from java.lang package). Like this, if there are thousand problems, thousand classes exist.

Instead of writing this type theory more and more, to get a clear concept, l give two programs one without handling exception and another with handling.

A program to illustrate the effect of NOT handling the exception.

File Name: ExceptionUnhandled.java

public class ExceptionUnhandled
{
  public static void main(String args[])
  {
    int a = 10, b = 0, c;
    System.out.println("Hello 1");

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

    System.out.println("Hello 2");
    System.out.println("Hello 3");
  }
}

ima

Observe the above screenshot. "Hello 1" is printed because it is there before a/b problem. By the time control comes to a/b, JVM finds problem to evaluate the result of division by zero and there by terminates the execution without printing "Hello 2" and "Hello 3", of course, while giving a message. Here, the message is important, see the screenshot.

What is happening internally and how the message generated?

When JVM, encounters division by zero problem, to give the message, an object of ArithmeticException is created and thrown. The thrown object of ArithmeticException gives the message.

Now what is exception handling?

With the above understanding, the definition becomes easy. Handling the exceptpion object thrown by JVM is known as exception handling. The advantage of exception handling is execution is not stopped.

A program to illustrate the effect of handling the exception.

File Name: ExceptionHandled.java

public class ExceptionHandled
{
  public static void main(String args[])
  {
    int a =10, b = 0, c;
    System.out.println("Hello 1");
    try
    {
      c = a/b;
      System.out.println(c);  
    }
    catch(ArithmeticException e)
    {
      System.out.println("Do not divide by zero sir."  + e );
    }
    System.out.println("Hello 2");
    System.out.println("Hello 3");
  }
}  

ima1

See the above screenshot.

Hello 2 and Hello 3 are also printed. This is the effect of exception handling mechanism. Observe the message given by catch block.

Let us explain the code.

  1. try and catch are keywords of Java used exclusively with exception handling mechanism only.
  2. Identify the trouble making statements and place them in the try block. How to identify the trouble making statements? Remember, when you ask the user to enter something at runtime, expect always there will be problem. Always exceptions are raised by user’s wrong input values.
  3. When the try block throws the exception, the catch block handles the exception and the program execution goes further to the last statement.
  4. If the try block does not throw the exception, the catch block is simply ignored (not executed).
  5. Provide a suitable exception handler, in catch block, that can handle the exception thrown by the try block successfully.
  6. In the above program, the successful exception handler is "ArithmeticException" for the problem of "division by zero".
  7. One of the ways of handling the exception is using try and catch blocks (other ways are using throws and throw keywords).
  8. Some problems raising exceptions:
    1. dividing an integer with zero.
      (represented by ArithmeticException)
    2. accessing an array element that does not exist.
      (represented by ArrayIndexOutOfBoundsException)
    3. connecting to a system that does not exist (by giving wrong IP address)
      (represented by MalformedURLException)
    4. trying to parse a string value that can not be parsed.
      (represented by NumberFormatException)
    5. using reference variable in place of an object
      (represented by NullpointerException)

Leave a Comment

Your email address will not be published.