Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 835
Alupkers Avatar asked Dec 24 '22 05:12

Alupkers


2 Answers

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.

like image 145
Jon Skeet Avatar answered Jan 10 '23 12:01

Jon Skeet


You can declare an unchecked exception in the throws clause, but, as you noted, it won't have any actual affect, besides signifying that the method may throw it. It definitely isn't uncommon to do so, and the JDK seems to have taken this approach (see, e.g., Integer#parseInt).

Regardless if you declare it in the throws clause or not, you should document it in the method's javadoc, which is the first place the people using your method would probably look.

like image 30
Mureinik Avatar answered Jan 10 '23 13:01

Mureinik