Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an analogue to Java IllegalStateException in Python?

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

like image 553
Tuure Laurinolli Avatar asked Nov 09 '09 14:11

Tuure Laurinolli


People also ask

How do you handle Java Lang IllegalStateException?

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.

Why do we get Java Lang IllegalStateException?

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.

Is IllegalStateException a runtime exception?

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.


2 Answers

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

like image 76
ddaa Avatar answered Sep 18 '22 09:09

ddaa


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 
like image 36
roskakori Avatar answered Sep 19 '22 09:09

roskakori