I have a simple library distributed as a .py file. I would like to raise an exception if the library is called from Python 2 instead of Python 3:
def _check_version():
if sys.version_info < (3,):
raise _____Exception('This library depends on Python 3 strings. Please ensure you are using Python 3 instead of Python 2')
What built-in exception should I raise? (How do I fill in the blank above?) The closest exception I can find among the builtin Exceptions is NotImplementedError. The DeprecationWarning feels close, but an exception is more appropriate in this case.
There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors.
As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.
Raising an exception is a technique for interrupting the normal flow of execution in a program, signaling that some exceptional circumstance has arisen, and returning directly to an enclosing part of the program that was designated to react to that circumstance.
Use raise when you know you want a specific behavior, such as: raise TypeError("Wanted strawberry, got grape.") Raising an exception terminates the flow of your program, allowing the exception to bubble up the call stack. In the above example, this would let you explicitly handle TypeError later.
Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in exceptions in Java.
I'd use RuntimeError
for this; there is no more specific exception.
raise RuntimeError("<pkg> needs Python 3.7 or later")
<pkg>
not some other package or Python itself, which would not be clear to non-Python users; having had to write production scripts that get used by non-Python users. Don't expect non-Python users to read or understand Python tracebacks.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