try语句的可选else子句的预期用途是什么?


当前回答

也许它的用法是:

#debug = []

def debuglog(text, obj=None):
    " Simple little logger. "
    try:
        debug   # does global exist?
    except NameError:
        pass    # if not, don't even bother displaying
    except:
        print('Unknown cause. Debug debuglog().')
    else:
        # debug does exist.
        # Now test if you want to log this debug message
        # from caller "obj"
        try:
            if obj in debug:
                print(text)     # stdout
        except TypeError:
            print('The global "debug" flag should be an iterable.')
        except:
            print('Unknown cause. Debug debuglog().')

def myfunc():
    debuglog('Made it to myfunc()', myfunc)

debug = [myfunc,]
myfunc()

也许这对你也有帮助。

其他回答

使用else样式和可读性是一个重要原因。将可能导致异常的代码放在处理异常的代码附近通常是个好主意。例如,比较这些:

try:
    from EasyDialogs import AskPassword
    # 20 other lines
    getpass = AskPassword
except ImportError:
    getpass = default_getpass

and

try:
    from EasyDialogs import AskPassword
except ImportError:
    getpass = default_getpass
else:
    # 20 other lines
    getpass = AskPassword

当异常不能提前返回或重新抛出异常时,第二个方法很好。如果可能的话,我会这样写:

try:
    from EasyDialogs import AskPassword
except ImportError:
    getpass = default_getpass
    return False  # or throw Exception('something more descriptive')

# 20 other lines
getpass = AskPassword

注意:答案从最近发布的副本复制在这里,因此所有这些“AskPassword”的东西。

如果执行落在try的底部(如果没有异常),else块中的语句将被执行。说实话,我从来没有找到过需要。

然而,处理异常注意到:

使用else子句更好 而不是向try中添加额外的代码 因为它避免意外 捕获非异常 由被保护的代码引发 尝试…除了声明。

因此,如果你有一个方法,例如,抛出一个IOError,你想捕捉它引发的异常,但如果第一个操作成功,你还想做其他事情,而你不想从那个操作中捕获IOError,你可能会写这样的东西:

try:
    operation_that_can_throw_ioerror()
except IOError:
    handle_the_exception_somehow()
else:
    # we don't want to catch the IOError if it's raised
    another_operation_that_can_throw_ioerror()
finally:
    something_we_always_need_to_do()

如果您只是在operation_that_can_throw_ioerror()后面加上另一个other_operation_that_can_throw_ioerror(), except将捕获第二次调用的错误。如果你把它放在整个try块之后,它会一直运行,直到finally之后。else可以让你确定

第二次操作只有在没有例外的情况下才会进行, 它在最后一个块之前运行,并且 它引发的任何ioerror都不会在这里被捕获

错误和异常#处理异常- docs.python.org

The try ... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example: for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines' f.close() The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.

我能想到的一种使用场景是不可预测的异常,如果您再次尝试,可以避免这种异常。例如,当try块中的操作涉及随机数时:

while True:
    try:
        r = random.random()
        some_operation_that_fails_for_specific_r(r)
    except Exception:
        continue
    else:
        break

但是如果可以预测异常,则应该始终在异常之前选择验证。然而,并不是所有的事情都可以预测,所以这种代码模式有它的一席之地。

try:
    statements # statements that can raise exceptions
except:
    statements # statements that will be executed to handle exceptions
else:
    statements # statements that will be executed if there is no exception

例子:

try:
    age=int(input('Enter your age: '))
except:
    print ('You have entered an invalid value.')
else:
    if age <= 21:
        print('You are not allowed to enter, you are too young.')
    else:
        print('Welcome, you are old enough.')

输出:

>>> 
Enter your age: a
You have entered an invalid value.
>>> RESTART
>>> 
Enter your age: 25
Welcome, you are old enough.
>>> RESTART
>>> 
Enter your age: 13
You are not allowed to enter, you are too young.
>>> 

复制自:https://geek-university.com/python/the-try-except-else-statements/