IllegalStateException is often used in Java when a method is invoked on an object in inappropriate state. What would you use instead in Python?
To avoid the IllegalStateException in Java, it should be ensured that any method in code is not called at an illegal or inappropriate time. Calling the next() method moves the Iterator position to the next element.
Indicates that the app has exceeded a limit set by the System. Thrown when an internal codec error occurs. 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.
IllegalStateException is the child class of RuntimeException and hence it is an unchecked exception. This exception is rise explicitly by programmer or by the API developer to indicate that a method has been invoked at the wrong time.
In Python, that would be ValueError
, or a subclass of it.
For example, trying to .read()
a closed file raises "ValueError: I/O operation on closed file".
ValueError
seems more like the equivalent to Java's IllegalArgumentException
.
RuntimeError sounds like a better fit to me:
Raised when an error is detected that doesn’t fall in any of the other categories. The associated value is a string indicating what precisely went wrong.
Most of the time you don't want to do any special error handling on such an error anyway, so the generic RuntimeError
should suffice out of the box.
In case you do want to handle it differently to other errors just derive your own exception from it:
class IllegalStateError(RuntimeError): pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With