Is there an analogue to Java IllegalStateException in Python?

JavaPythonException

Java Problem Overview


IllegalStateException is often used in Java when a method is invoked on an object in inappropriate state. What would you use instead in Python?

Java Solutions


Solution 1 - Java

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".

Solution 2 - Java

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

Solution 3 - Java

ValueError sounds appropriate to me:

>Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTuure LaurinolliView Question on Stackoverflow
Solution 1 - JavaddaaView Answer on Stackoverflow
Solution 2 - JavaroskakoriView Answer on Stackoverflow
Solution 3 - Javamatt bView Answer on Stackoverflow