Reputation: 4493
I have a class which offers a public method that must only be called once. What would be a proper exception to throw in case its called again?
My current candiate is RejectedExecutionException
Upvotes: 1
Views: 397
Reputation: 140457
I suggest something completely different:
Consider if you can change your design.
The fact that your interface allows to only call a method once puts a constraint on the users of your interface. Interfaces should make it easy to use them "the right way"; and make it hard to use them the wrong way.
So instead of thinking about the exception type to throw ... think about solutions to simply make it impossible to misuse the interface.
For example, make the method private - and invoke only within the constructor of some internal singleton object. That (more or less) guarantees that the method will be called exactly once.
Upvotes: -1
Reputation: 393831
IllegalStateException
may be appropriate, or something similar. For example, calling Thread::start twice would throw IllegalThreadStateException
.
Upvotes: 4