Should I declare an unchecked exception?

I've got a method which invokes another method like this:

public void m1() {
    m2(10);
}

public void m2(int v) {
    if(v < 10)
        throw new MyException();
}

public class MyException extends RuntimeException{ }

Now, I'd like to notify clients who are going to use m1() that it might throw MyException. Is it OK if I declare it like this:

public void m1() throws MyException{
    m2(10);
}

I'm not sure about it as I used to use throws declaration with checked exceptions. Is it common to do so with unchecked ones?

Jon Skeet
people
quotationmark

You can do so - and it'll show up in the Javadoc, I believe. But it won't force any callers to handle the exception, so you're still basically relying on the users (developers calling your code) to be diligent enough to check the documentation. If that's sufficient for you, go for it - otherwise, change MyException to be a checked exception.

As for whether it's common to declare unchecked exceptions that might be thrown - I would say I've seen it often enough for it not to be particularly surprising, but it's not a widely-used practice.

people

See more on this question at Stackoverflow