Python:嵌套的 try catch 处理

rad*_*rad 1 python nested try-catch

目前我有一些这样的代码

try:
    somecode
except Exception as Error:
    fallbackcode
Run Code Online (Sandbox Code Playgroud)

现在我想在回退代码中添加另一个回退 在 python 中进行嵌套 try/catch 的最佳实践是什么?

try:
    somecode
except Exception as Error:
    try:
        fallbackcode
    except Exception as Error:
        nextfallbackcode
Run Code Online (Sandbox Code Playgroud)

产生意图错误

AK4*_*K47 5

您应该能够准确地在问题中实现嵌套的 try/except 块。

这是另一个例子:

import os

def touch_file(file_to_touch):
    """
    This method accepts a file path as a parameter and
    returns true/false if it successfully 'touched' the file
    :param '/path/to/file/'
    :return: True/False
    """    
    file_touched = True

    try:
        os.utime(file_to_touch, None)
    except EnvironmentError:
        try:
            open(file_to_touch, 'a').close()
        except EnvironmentError:
            file_touched = False

    return file_touched
Run Code Online (Sandbox Code Playgroud)