Are Python runtime errors excluded (except SyntaxError)?

If I understand correctly when I run the Python program, the Python interpreter generates bytecode (the .pyc file that appears next to the .py source), unless the source contains a syntax error.

Does the bytecode compiler throw any other exceptions or all other exceptions that occur at runtime when .pyc code is executed?

+8
python exception runtime-error
source share
2 answers

Well, any type of exception can technically be raised at runtime via raise <exception> . But I assume that you understand this and ask what exceptions can be raised when Python interprets your code (before execution). In fact, there are quite a lot of them:

  • SyntaxError : This is expressed by the parser when reading the code. This is the result of invalid syntax such as an unbalanced bracket, using the keyword in the wrong place, etc.

  • IndentationError : This is a subclass of SyntaxError and occurs every time your code is incorrectly indented. An example is:

     if condition: line_indented_4_spaces line_indented_3_spaces 
  • TabError : This is a subclass of IndentationError and occurs when you inconsistently mix tabs and spaces in the source file.

  • SystemError : This is SystemError by the interpreter when an internal operation fails. A meeting usually means that your Python installation is messed up and may need to be reinstalled.

  • MemoryError : This is similar to a SystemError and can be raised when an internal operation fails due to lack of memory.

All of these exceptions can be raised before your code even starts executing. The first three are caused by a corrupt source file and can be resolved by simply correcting the syntax or indentation. The last two, however, are raised by the interpreter itself for internal operations that fail. This means that they are rare, but also that they are more serious and not so easy to fix.

+4
source share

Typically, when you work with Python code, there is no compilation step, so I would say that all errors in Python, including SyntaxErrors, are runtime errors.

For example, let's write this file:

 in xrange(5): 

This is obviously just absurd (we will call it nonsense.py), but it allows you to run the interpreter:

 $ python >>> try: ... import nonsense ... except SyntaxError: ... print("A syntax error occurred at runtime!") ... A syntax error occurred at runtime! >>> 

So, you have it - SyntaxError was raised and caught at runtime, which, in my opinion, at least indicates that this is a runtime error.

+1
source share

All Articles