简体   繁体   中英

Which exception to throw if a method is called again when it must only be called once?

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

IllegalStateException may be appropriate, or something similar. For example, calling Thread::start twice would throw IllegalThreadStateException .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM