python - 如果 try 语句在 python 中成功,则运行代码

标签 python error-handling try-catch

我想知道在 python 中是否有一种简单的方法来运行代码,如果 try 语句成功但不在 try 语句本身中。那是 else 或 finally 命令的作用吗(我不理解他们的文档)?我知道我可以使用这样的代码:

successful = False
try:
    #code that might fail
    successful = True
except:
    #error handling if code failed
if successful:
    #code to run if try was successful that isn't part of try

但我想知道是否有更短的方法。

最佳答案

你想要else:

for i in [0, 1]:
    try:
        print '10 / %i: ' % i, 10 / i
    except:
        print 'Uh-Oh'
    else:
        print 'Yay!'

关于python - 如果 try 语句在 python 中成功,则运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2792568/

相关文章:

行向量矩阵之间的python numpy欧几里得距离计算

python - Django 模板中的 "TemplateSyntaxError Invalid block tag: ' trans '"错误

python - 如何在Python中使用“尝试和异常”引发打印消息错误?

java - 为什么 Kotlin 会收到这样的 UndeclaredThrowableException 而不是 ParseException?

php - 如何捕获PHP错误作为软验证

python - 如何计算 tar 文件中每个文件的 shasum

python - 无法在具有无限循环的 boost.python 模块中通过 Ctrl-c 终止进程

ios - 在 Swift 中处理错误

error-handling - Powershell错误输出抑制(再次)

python - 由于 Python 中的请求不安全的 URL 而捕获 SSLError?