-1

I want to restrict my function divide to always be called from a try block. But when the function is called from main, without using try block, it does not show "Unhandled Exception" error?

class Main {
    public static void main(String[] args) {
        System.out.println(Main.divide(5.0f, 2.0f));
        System.out.println(divide(5.0f, 2.0f));
    }

    static float divide(float x, float y) throws ArithmeticException {
        if (y == 0)
            throw new ArithmeticException("Cannot divide by 0!");
        else
            return x/y;
    }
}

Output:

2.5
2.5
  • 2
    `ArithmeticException` is a RuntimeException not a checked exception. Create a new Exception extend from Exception to create a checked exception – Jens Jan 25 '23 at 08:41
  • 2
    `ArithmeticException` is also unchecked by design. Instead of trying to catch division by zero as an exception, avoid producing code that attempts to divide by zero. – jsheeran Jan 25 '23 at 08:45

1 Answers1

-2

To make use of "throws" keyword to throw the checked exception, you can force the calling method to handle the exception.

Make this change:

From:

static float divide(float x, float y) throws ArithmeticException {

To:

// Custom checked exception
static class UserDefinedException extends Exception {  
    public UserDefinedException(String str) {  
        super(str);  
    }  
}  

// Good approach 
static float divide(float x, float y) throws UserDefinedException {
   if (y == 0)
        throw new UserDefinedException("Cannot divide by 0!");
   else
        return x/y;
}

// Bad approach
//static float divide(float x, float y) throws Exception { ... }
Wing Kui Tsoi
  • 474
  • 1
  • 6
  • 16