5

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?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Alupkers
  • 223
  • 1
  • 9

2 Answers2

8

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 1
    There are counter examples in the JDK.For example, ArrayList#get doesn't have a throws clause for IndexOutOfBoundsException. – Eran May 29 '16 at 07:27