Python Try-Except inside of Function

后端 未结 6 1897
旧巷少年郎
旧巷少年郎 2020-12-11 23:03

I\'ve got a pretty good understanding of python\'s try-except clause, but I\'m encountering problems when trying to put it inside of a function.

>>>         


        
相关标签:
6条回答
  • 2020-12-11 23:44

    The name error is happening before it ever gets into tryAppend. It evaluates the value of foo when trying to pass it to the function. This works:

    def tryAppend(child, parent):
        parent.append(child)
    
    var1 = []
    try:
        tryAppend(foo, var1)
    except NameError:
        print 'WRONG NAME'
    
    0 讨论(0)
  • 2020-12-11 23:46

    foo exception happens even before you enter the function tryAppend() i.e. outside of the function.

    0 讨论(0)
  • 2020-12-11 23:52

    For someone who is looking for how to use try except construction inside of the function. I am not sure whether it is a good programming style, but it works.

    You can put string arguments to the function. It will be evaluated correctly and then you can use exec inside of the function:

    def tryAppend(child, parent):
        try:
            script = parent + '.append(' + child + ')'
            exec script
            return parent
        except NameError:
            print "WRONG NAME"
    var1 = []
    var2 = 'test2'
    tryAppend('var2', 'var1')
    tryAppend('foo', 'var1')
    
    0 讨论(0)
  • 2020-12-11 23:56

    The NameError is being thrown when the name 'foo' is evaluated, which is before entering the function. Therefore the try/except within the function isn't relevant.

    0 讨论(0)
  • 2020-12-11 23:59

    tryAppend(foo, var1) is evaluated (roughly) in this order:

    1. Fetch the object tryAppend references
    2. Fetch the object foo references
    3. Fetch the object var1 references
    4. Call the first with the second and third as arguments (=do whatever the function tryAppend does, uncluding the try-except)

    The error occurs at #2, long before the function and the try block is entered. In fact, the try block cannot to throw a NameError, as the only names used are parent and child, both being arguments and thus always available (if .append does not exist, that's an AttributeError).

    In the same way, the following code will not print "caught it" because the exception is raised before the try block is executed:

    raise Exception("Catch me if you can")
    try:
        pass # do nothing
    except:
        print "caught it"
    
    0 讨论(0)
  • 2020-12-12 00:03

    This has nothing to do with your exception handler. The error you are seeing is because "foo" is not defined anywhere.

    0 讨论(0)
提交回复
热议问题