user3579404
user3579404

Reputation: 3

Error: cannot find symbol for Exceptions in Java

I am writing a very simple program in Java that tries to divide 10 by a user-entered number and catches a DivideByZeroException. Here is the code:

public class EnhancedCatchExceptions6 {

    public static void main(String[] args) {

        System.out.println();

        for (int i = 0 ; i < i; i++) {

            try {
                int b = Input.getInt("Enter an integer to divide by:");
                divide(10, b);
                break;
            } catch (DivideByZeroException e) {
                System.out.println("Error: Divided by zero. Try again.\n");
            }
        }
    }

    public static int divide(int x, int y) throws DivideByZeroException {

        System.out.println();

        int result = 0;

        try {result = x/y;}
            catch (ArithmeticException e) {throw new DivideByZeroException(y);}

        return result;

    }
}

For some reason is returns an error: cannot find symbol for every 'DivideByZeroException.' If I change DivideByZeroException to Exception it does not return that error. The same error appears when I was writing other programs with other exceptions.

I don't understand why this error is returned and I would appreciate any help. Thanks!

Upvotes: 0

Views: 4471

Answers (1)

Alexey Malev
Alexey Malev

Reputation: 6531

Most likely this is happening because you forget to import your DivideByZeroException. Change the first lines of your class adding:

import your.package.name.DivideByZeroException;

and you should be fine. Do not forget to use real package name of yours, of course.

The other guess - if you want a class that represents an exception and comes with JDK, not your own, consider replacing DivideByZeroException with ArithmeticException.

Upvotes: 2

Related Questions