JavaDeveloper
JavaDeveloper

Reputation: 5660

What error should be thrown for impossible conditions?

public static double findLCM (int num1, int num2) {

        for (int i = 1; i <= num2; i++) {
            double mult = big * i;
            if (mult % small == 0) {
                return mult;
            }
        }
        throw new Error("Error");
    }

As we know, it is impossible to not have an LCM. Please dont suggest me workarounds for the code like return variable after breaking from for loop etc. This code is custom made to understand the exception to be thrown.

Upvotes: 1

Views: 594

Answers (3)

ndm13
ndm13

Reputation: 1239

Since this is a high-ranking search result, I felt the need to add a response. @UnknownJoe left a comment on the question that, in my opinion, should be the correct answer for the general case, while @manouti's answer (accepted) is the correct answer for the specific case.

If there is any chance that a section of code could be accessed during the execution of the program due to invalid arguments being passed to the method, then IllegalArgumentException is the correct exception to throw; after all, it was an illegal argument that led to that code being executed. In the example provided, if I passed a 0 in as the second argument, I'd have the exception thrown.

My personal use case for this was with MessageDigest algorithms. Since a known set of algorithms has been provided since Java 1.5, I can feel free to directly reference any of these by name and not worry about the potential NoSuchAlgorithmException. While I could swallow the exception, wrapping it in an IllegalStateException allows me to pass it up the chain if my code's being run on a non-standard implementation, or if something's very wrong with the environment; more importantly, however, I'll know why my program is failing.

So in short: if your code can be accessed accidentally by providing invalid arguments, use InvalidArgumentException. If your code cannot be accessed normally and only by a fluke of the JVM, use IllegalStateException.

Upvotes: 0

Deep
Deep

Reputation: 98

I think you can use Exception

You can say:

throw new Exception("Error");

This will solve you problem. I am not 100 % sure but it worked for me many times.

Upvotes: 0

M A
M A

Reputation: 72854

The closest fit may be an IllegalArgumentException:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

Upvotes: 1

Related Questions