Python 关于捕获任何异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4990718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
About catching ANY exception
提问by user469652
How can I write a try/exceptblock that catches all exceptions?
如何编写一个捕获所有异常的try/except块?
采纳答案by Tim Pietzcker
You can but you probably shouldn't:
你可以,但你可能不应该:
try:
do_something()
except:
print "Caught it!"
However, this will also catch exceptions like KeyboardInterruptand you usually don't want that, do you? Unless you re-raise the exception right away - see the following example from the docs:
但是,这也会捕获异常,KeyboardInterrupt而您通常不希望这样,对吗?除非您立即重新引发异常 - 请参阅文档中的以下示例:
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
回答by Yuval Adam
try:
whatever()
except:
# this will catch any exception or error
It is worth mentioning this is not proper Python coding. This will catch also many errors you might not want to catch.
值得一提的是,这不是正确的 Python 编码。这也会捕获许多您可能不想捕获的错误。
回答by Duncan
Apart from a bare except:clause (which as others have said you shouldn't use), you can simply catch Exception:
除了一个裸except:条款(正如其他人所说你不应该使用的),你可以简单地 catch Exception:
import traceback
import logging
try:
whatever()
except Exception as e:
logging.error(traceback.format_exc())
# Logs the error appropriately.
You would normally only ever consider doing this at the outermost level of your code if for example you wanted to handle any otherwise uncaught exceptions before terminating.
您通常只会考虑在代码的最外层执行此操作,例如,如果您想在终止之前处理任何其他未捕获的异常。
The advantage of except Exceptionover the bare exceptis that there are a few exceptions that it wont catch, most obviously KeyboardInterruptand SystemExit: if you caught and swallowed those then you could make it hard for anyone to exit your script.
的优势,except Exception在裸露的except是,有少数例外,它不会赶上,最明显KeyboardInterrupt和SystemExit:如果你抓住了,吞下这些,那么你可以让任何人都很难离开你的脚本。
回答by Joshua Burns
Very simple example, similar to the one found here:
非常简单的示例,类似于此处找到的示例:
http://docs.python.org/tutorial/errors.html#defining-clean-up-actions
http://docs.python.org/tutorial/errors.html#defining-clean-up-actions
If you're attempting to catch ALL exceptions, then put all your code within the "try:" statement, in place of 'print "Performing an action which may throw an exception."'.
如果您试图捕获所有异常,请将所有代码放在“try:”语句中,而不是“打印”执行可能引发异常的操作。””。
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."
In the above example, you'd see output in this order:
在上面的示例中,您将按以下顺序看到输出:
1) Performing an action which may throw an exception.
1) 执行可能引发异常的操作。
2) Finally is called directly after executing the try statement whether an exception is thrown or not.
2) 无论是否抛出异常,都在执行try语句后直接调用finally。
3) "An exception was thrown!" or "Everything looks great!" depending on whether an exception was thrown.
3)“抛出异常!” 或“一切看起来都很棒!” 取决于是否抛出异常。
Hope this helps!
希望这可以帮助!
回答by vwvolodya
You can do this to handle general exceptions
您可以这样做来处理一般异常
try:
a = 2/0
except Exception as e:
print e.__doc__
print e.message
回答by gitaarik
To catch all possible exceptions, catch BaseException. It's on top of the Exception hierarchy:
要捕获所有可能的异常,请 catch BaseException。它位于异常层次结构的顶部:
Python 3: https://docs.python.org/3.5/library/exceptions.html#exception-hierarchy
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:https: //docs.python.org/2.7/library/exceptions.html#exception-hierarchy
try:
something()
except BaseException as error:
print('An exception occurred: {}'.format(error))
But as other people mentioned, you would usually not need this, only for specific cases.
但正如其他人所提到的,您通常不需要这个,仅适用于特定情况。
回答by Danilo
I've just found out this little trick for testing if exception names in Python 2.7 . Sometimes i have handled specific exceptions in the code, so i needed a test to see if that name is within a list of handled exceptions.
我刚刚发现了这个用于测试 Python 2.7 中是否有异常名称的小技巧。有时我在代码中处理了特定的异常,所以我需要进行测试以查看该名称是否在已处理异常列表中。
try:
raise IndexError #as test error
except Exception as e:
excepName = type(e).__name__ # returns the name of the exception
回答by grepit
There are multiple ways to do this in particular with Python 3.0 and above
有多种方法可以做到这一点,尤其是在 Python 3.0 及更高版本中
Approach 1
方法一
This is simple approach but not recommended because you would not know exactly which line of code is actually throwing the exception:
这是一种简单的方法,但不推荐,因为您不会确切知道哪一行代码实际上抛出了异常:
def bad_method():
try:
sqrt = 0**-1
except Exception as e:
print(e)
bad_method()
Approach 2
方法二
This approach is recommended because it provides more detail about each exception. It includes:
建议使用此方法,因为它提供了有关每个异常的更多详细信息。这包括:
- Line number for your code
- File name
- The actual error in more verbose way
- 您的代码的行号
- 文档名称
- 更详细的实际错误
The only drawback is tracback needs to be imported.
唯一的缺点是需要导入回溯。
import traceback
def bad_method():
try:
sqrt = 0**-1
except Exception:
print(traceback.print_exc())
bad_method()

