Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the appropriate built-in Exception to raise if your library is used with the wrong Python Version?

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.

like image 276
Josiah Yoder Avatar asked Sep 11 '17 20:09

Josiah Yoder


People also ask

What are the 3 major exception types in Python?

There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors.

How do you raise a specific exception in Python?

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.

What is an exception What are the problems if the exception is raised?

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.

When should you raise an exception Python?

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.

What are built in exceptions?

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.


2 Answers

I'd use RuntimeError for this; there is no more specific exception.

like image 175
Martijn Pieters Avatar answered Oct 04 '22 23:10

Martijn Pieters


raise RuntimeError("<pkg> needs Python 3.7 or later")

  • so that the stderr both gives information and can be parsed automatically/ logged
  • and makes it clear that the culprit is <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.
like image 39
smci Avatar answered Oct 04 '22 21:10

smci