Home‎ > ‎Applied Core Java‎ > ‎Exception Handling‎ > ‎

Arithmetic Exception

divide Problem : How you will handle Arithmetic exception?               

Program :

Step 1 - Coding

Create a text file c:\sunilos\TestArithmetic.java  and copy below contents.

/*
 *Program for arithmetic operation.
 */

public class TestArithmetic {

    public static void main(String[] args) {
        // case1(); //Normal Flow
        // case2();  // Exception
        case3();//Exception Handling

    }

    /**
     * Normal arithmetic calculation
     */

    public static void case1() {

        int k = 5;
        int i = 15;

        double div = i / k;

        System.out.println("Div is " + div);
    }

    /** Divide by Zero that raised an exception */

    public static void case2() {

        int k = 0;
        int i = 15;

        double div = i / k;

        System.out.println("Div is " + div);
    }

    /**
     * Handles exceptional condition and print custom message 'Divident can not be Zero'
     */

    public static void case3() {

        int k = 0;
        int i = 15;

        try {
            double div = i / k;
            System.out.println("Div is " + div);

        } catch (ArithmeticException e) {
            System.out.println("Division can not be Zero");
        }

    }
}

Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy  into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. Compile  with help of 
    • javac TestArithmetic.java command.  Compiled class file will be created in the same folder
  5. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your  java program from command prompt with help of 
    • java TestArithmetic  command.
  3. You can uncomment case1, case2, and case3 one by one and check output.

Output

case 1: Normal Flow
Div is 5

case 2: Exception
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at com.sunilos.exception.x.TestArithmetic.case2(TestArithmetic.java:33)
    at com.sunilos.exception.x.TestArithmetic.main(TestArithmetic.java:7)
case3: Exception Handling
Division can not be Zero


<<Previous | Next>>
ċ
Sunil Sahu,
Oct 16, 2015, 3:56 AM
Comments