Reputation: 1262
Say you have a class called Timer
. When a user tries to call the method Timer#start()
, the code checks if the timer has already been started. If it has, then it can't start it again. Now, say this class is a part of a library/API. The developer can't know that the method isn't being called inappropriately, so they want to bring attention to any improper calls. The two ways to do so would be to a) print a simple error message (so-and-so has called a method inappropriately), or b) throw an exception.
In my opinion, the exception that would make the most sense is an IllegalAccessException, though this isn't its intention as stated by Sun. However, I've seen it used in cases that have nothing to do with visibility and are simply throwing it to call attention to a bad call. My question is, would this situation call for (haha, pun) said exception, or is there a better one suited to it? Or, would it be best to create a new one or to simply print an error line?
Upvotes: 1
Views: 435
Reputation: 2279
Based on your requirement it seems IllegalStateException
is more appropriate. As your class is managing some state of the Timer.
From Java Doc for IllegalStateException
:
Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.
From Java doc for IllegalAccessException
, it says:
An IllegalAccessException is thrown when an application tries to reflectively create an instance (other than an array), set or get a field, or invoke a method, but the currently executing method does not have access to the definition of the specified class, field, method or constructor.
so, IllegalAccessException
is not at all appropriate.
Upvotes: 1
Reputation: 77206
This condition very clearly doesn't match the semantics of IllegalAccessException
, but it sounds like an exact fit for IllegalStateException
.
Upvotes: 0