Instead of catching exceptions, the try and catch blocks give result as infinity

StackOverflow https://stackoverflow.com/questions/23186867

  •  06-07-2023
  •  | 
  •  

문제

In both my java an C++ programs, I have put a simple try/catch block to catch a divide by zero exception. Instead of addressing the problem, the program says the answer is infinity. Why is this happening?

Java (C++ almost exactly like this):

import java.util.Scanner;
import java.lang.ArithmeticException;
public class Expiriment {



    static double a;
    static double b;


    public static void main (String [] args){

        try {

        Scanner input = new Scanner (System.in);
            System.out.println("Enter first Number");
            a = input.nextInt();
            System.out.println("Enter 2nd number");
            b = input.nextInt();
            System.out.println("Answer is:"+ a/b);  

        }
        catch (ArithmeticException e) {
            double f = 0;
            System.err.println (e+" "+"Cannot perform operation.");
            System.out.println("Answer is:" + f);
        }


        }

    }
도움이 되었습니까?

해결책

Do not compare Java's try/catch with C++'s try/catch. Division by zero in a C++ program is not a C++ exception.

Please see here:

Catching exception: divide by zero

다른 팁

IEEE754 floating point division is defined to return infinity for nonzero a and 0 b, or NaN if you divide 0/0. Hence, you get such a result in your print statement.

Wikipedia:

Division by zero (an operation on finite operands gives an exact infinite result, e.g., 1/0or log(0)) (returns ±infinity by default).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top