DAA Program 3 Exception

Write a Java program to read two integers a and b. Compute a/b and print, when b is not zero. Raise an exception when b is equal to zero.

1 package program3.exception;
2 
3 public class Division {
4         private float n1;
5         private float n2;
6 
7         public Division(float n1, float n2) {
8                 super();
9                 this.n1 = n1;
10                this.n2 = n2;
11        }
12
13        public float computeDiv() {
14                if (n2 == 0) {
15                        throw new ArithmeticException("/ by zero");
16                } else {
17                        return (n1 / n2);
18                }
19        }
20}
21
22package program3.exception;
23
24import java.util.Scanner;
25
26public class ExceptionDemo {
27
28        public static void main(String[] args) {
29
30                Scanner s = new Scanner(System.in);
31
32                System.out.println("Enter numerator: ");
33                int n1 = s.nextInt();
34
35                System.out.println("Enter denominator: ");
36                int n2 = s.nextInt();
37
38                Division div = new Division(n1, n2);
39
40                try {
41                        float result = div.computeDiv();
42                        System.out.println("Result: " + result);
43                } catch (ArithmeticException e) {
44                        e.printStackTrace();
45                }
46
47        }
48
49}


OUTPUT :

Run 1:

Enter numerator:

2

Enter denominator:

0

java.lang.ArithmeticException: / by zero

        at program3.exception.Division.computeDiv(Division.java:15)

        at program3.exception.ExceptionDemo.main(ExceptionDemo.java:20)

Run 2:

Enter numerator:

4

Enter denominator:

2

Result: 2.0


No comments:

Post a Comment

Online Certifications

Python for Beginners Offered by: Christian Drumm, Stephan Jacobs Course dates: 2022-04-05 to 2022-06-01 Topics Python Fundamentals Lists and...