【问题标题】:How to make python script continue after raise statement如何在raise语句后使python脚本继续
【发布时间】:2019-07-06 08:22:37
【问题描述】:

如果我的 else 语句在第一个函数中执行,我需要在 raise 语句之后执行我的第二个函数清理

但由于这是一个例外,因此它不起作用,因此我的第二个函数 cleanup() 不起作用。

请注意:如果找不到字符串,我需要在第一个函数中引发异常

请让我知道我能做些什么来克服这个问题。非常感谢任何帮助

我已经尝试 if else 通过调用 else 的 raise 语句来实现这一点,但它根本不起作用,因此我被卡住了。请帮忙

import os
import re

def validated():
    if 'line is up , protocol is up' in open('C:/Users/diwak/Desktop/1.txt').read():
        print("true")

    else:
        raise ("Not found")

def cleanup():
    print ("cleanup still performed")


print (validated())
(cleanup())

我的期望是两个函数都能执行:

1) 第一个函数引发异常错误 2) 已执行清理功能

实际输出:

如果条件不匹配,程序会退出第一个函数本身

【问题讨论】:

  • 我建议看看try .. except 在 Python 中是如何工作的。
  • 我试过了,但不幸的是它没有奏效......感谢您的帮助
  • 请任何人帮忙
  • 请大家帮忙

标签: exception python-3.6


【解决方案1】:

我想这是需要的(虽然它看起来很奇怪):

def validated():
    try:
        if 'helo' in 'hello world':
            print("true")
        else:
            raise Exception("Not found")
    except:
        cleanup()

def cleanup():
    print ("cleanup still performed")

validated()

【讨论】:

  • 哇,你这个摇滚哥们,其实我是在 except 中添加 else 部分,我多么愚蠢………………
【解决方案2】:
def validated():
    try:
        if 'line is up , protocol is up' in open('C:/Users/diwak/Desktop/1.txt').read():
            print("true")
        else:
            print("string not found")
            raise Exception("Not found")
    except:
        pass



def cleanup():
    print ("but cleanup still performed")

validated()
cleanup()

如果您同意,我认为 pass 也应该有效

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 2014-10-20
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多