简体   繁体   中英

Can some one explain the use NameError in try except statements?

I use the NameError in a try except statement, like the one below:

from tkinter import *

# Functions
def chordLabelTextGen(CHORDS, current_chord):
    while True:
        try:
            return_value = CHORDS
            current_chord_pos = return_value.index(current_chord)
            return_value.remove(current_chord_pos)
            return return_value
        except NameError:
            return_value = CHORDS
            return return_value

# Main    
ROOT = Tk()
ROOT.geometry("600x400")
ROOT.title("Chord Changes Log")
STANDARD_TUNING_CHORDS = ["A","B","C","D","E","F","G"]

chord_names = chordLabelTextGen(STANDARD_TUNING_CHORDS, current_chord)
current_chord = chord_names[0]
chord_names = chordLabelTextGen(STANDARD_TUNING_CHORDS, current_chord)
print (chord_names)

But when I run it through IDLE it returns this error message:

Traceback (most recent call last):
  File "C:/Users/Jack/Desktop/Python Projects/Gutiar chord changes log PROTOTYPE.py", line 26, in <module>
    chord_names = chordLabelTextGen(STANDARD_TUNING_CHORDS, current_chord)
NameError: name 'current_chord' is not defined

I thought the expect statement would would like an else statement and run the second block instead, but it doesn't seem to work this way.
Can anyone explain this to me?

The problem is the NameError exception is raised in the main and not in your function. current_chord doesn't exist in your scope when you're calling the function, so the program fail before entering in the function, when it tried to put arguments on the stack...

If you put something like this:

try:
    chord_names = chordLabelTextGen(STANDARD_TUNING_CHORDS, current_chord)
except NameError:
    print("Damn, there's an error")

... you'll see the error message. Besides, it's not very beautiful to handle undefined variables with try/except blocks. You should know when variable exists and when not.

exception NameError Raised when a local or global name is not found. This applies only to unqualified names. The associated value is an error message that includes the name that could not be found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM