但是,这也会捕获像 KeyboardInterrupt 这样的异常,你通常不希望这样,是吗?除非您立即重新引发异常 - 请参阅以下示例from the docs:
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as (errno, strerror):
print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
try:
print "Performing an action which may throw an exception."
except Exception, error:
print "An exception was thrown!"
print str(error)
else:
print "Everything looks great!"
finally:
print "Finally is called directly after executing the try statement whether an exception is thrown or not."
7 回答
你可以,但你可能不应该:
但是,这也会捕获像
KeyboardInterrupt
这样的异常,你通常不希望这样,是吗?除非您立即重新引发异常 - 请参阅以下示例from the docs:除了一个完整的
except:
条款(正如其他人所说的那样你不应该使用),你可以简单地 grab Exception:您通常只会考虑在代码的最外层执行此操作,例如,您希望在终止之前处理任何其他未捕获的异常 .
except Exception
优于except
的优点是,它有一些例外,它们不会捕获,最明显是KeyboardInterrupt
和SystemExit
:如果你 grab 并吞下那些,那么你可能会让任何人都难以退出你的脚本 .您可以这样做来处理一般异常
很简单的例子,类似于这里找到的例子:
http://docs.python.org/tutorial/errors.html#defining-clean-up-actions
如果您尝试捕获所有异常,则将所有代码放在“try:”语句中,代替'print'执行可能引发异常的操作 . “' .
在上面的示例中,您将按以下顺序查看输出:
1)执行可能引发异常的动作 .
2)最后在执行try语句后直接调用是否抛出异常 .
3)“抛出异常!”或者“一切看起来都很棒!”取决于是否抛出异常 .
希望这可以帮助!
要捕获所有可能的异常,请 grab
BaseException
. 它位于异常层次结构之上:Python 3:https://docs.python.org/3.5/library/exceptions.html#exception-hierarchy
Python 2.7:https://docs.python.org/2.7/library/exceptions.html#exception-hierarchy
但正如其他人提到的那样,除非你有充分的理由,否则你通常不会这样做 .
我刚刚发现了这个小技巧,用于测试Python 2.7中的异常名称 . 有时我在代码中处理了特定的异常,所以我需要一个测试来查看该名称是否在处理的异常列表中 .
值得一提的是,这不是正确的Python编码 . 这将捕获您可能不想捕获的许多错误 .