문제

I'm just get in getting my hands wet in exception handling in Java. My question is this: Are exception constructors required in the code in order for exceptions to be handled or the try-catch-finally block should be enough? I'm saying this because, running the program below. The output were the same, with or without the THROW statement inside the quotient(int number1, int number2) method. Below was the output: run:


Enter two integers: 9 0 Exception: an integer cannot be divided by Zero After the exception handling the program continues....


public class ExceptionHandling {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Enter two integers: ");
        int number1 = input.nextInt();
        int number2 = input.nextInt();

        try {
            int result = quotient(number1, number2);
            System.out.println(number1 + "/" + number2 + " is " + number1 / number2);

        }
        catch (ArithmeticException ex) {
            System.out.println("Exception: an integer cannot be divided by Zero");
        }

       System.out.println("After the exception handling, the program continues....");

    }


    public static int quotient(int number1, int number2) {
        if ( number2 == 0) {
            throw new ArithmeticException("Divisor cannot be Zero");
        }

        return number1 / number2;

    }

}
도움이 되었습니까?

해결책

The reason the output was the same with or without your throw statement is that Java already throws an instance of ArithmeticException when you divide a number by zero. Your condition would only make sense if you throw a different exception.

public class ArithmeticException extends RuntimeException

Thrown when an exceptional arithmetic condition has occurred. For example, an integer "divide by zero" throws an instance of this class. ArithmeticException objects may be constructed by the virtual machine as if suppression were disabled and/or the stack trace was not writable.

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