Uncaught NameError in try except block

The following code has been tested with (cpython) Python 3.6.4 and Python 2.7.14.

When the explicit statement is raise ValueErrorcommented out, the following code runs and prints "Hello!" and then "Peace!" although the symbol ValueErrodoes not exist.

Uncomment the statement raise ValueErrorand the ValueError will be raised and the expected one NameError: name 'ValueErro' is not definedwill be raised.

try:
    print("Hello!")
    # raise ValueError("?")
except ValueErro:
    print("Error!")
finally:
    print("World!")

I expected that a NameError would display well before processing the exception block at runtime.

Is there any other syntax that checks names / characters more aggressively during a parsing session?

Is this an implementation error?

Thanks for reading!

+4
source share
2 answers

@DYZ , .

https://docs.python.org/3/tutorial/errors.html#handling-exceptions

try .

  • try ( () try except).

  • , except , try .

, .

https://dbaktiar-on-python.blogspot.com/2009/07/python-lazy-evaluation-on-exception.html

-

:

# Explicitly bind the Exception Names in a non-lazy fashion.
errors = (KeyboardInterrupt, ValueErro) # Caught!
try:
    print("Hello!")
    raise ValueError("?")
except errors:
    print("Error!")
finally:
    print("World!")

-

tl; dr - except , try .

+1

. :

myexcept.py :

class ValueErro(Exception):
    pass

:

import_myexcept = False
if import_myexcept:
    from myexcept import ValueErro

try:
    print("Hello!")
    raise ValueError("?")
except ValueErro:
    print("Error!")
finally:
    print("World!")

, : NameError: name 'ValueErro' is not defined.

: import_myexcept = True, , except ValueErro:, ValueErro NameError.

0

Source: https://habr.com/ru/post/1692511/


All Articles