【发布时间】:2018-06-20 09:51:29
【问题描述】:
当我需要来自用户的输入数据或尝试启动线程时,我通常使用 try-except 块。但是是否有一些经验法则可以告诉我们什么时候绝对应该使用 try-except 块?从技术上讲,没有什么能阻止你做一些“聪明”的事情:
try:
print("Hello world")
except:
print("Bye bye world")
每当我觉得可能出现以下错误之一时,是否应该实施 try-except 块?
$ python -m pydoc builtins
BaseException
Exception
ArithmeticError
FloatingPointError
OverflowError
ZeroDivisionError
AssertionError
AttributeError
BufferError
EOFError
ImportError
ModuleNotFoundError
LookupError
IndexError
KeyError
MemoryError
NameError
UnboundLocalError
OSError
BlockingIOError
ChildProcessError
ConnectionError
BrokenPipeError
ConnectionAbortedError
ConnectionRefusedError
ConnectionResetError
FileExistsError
FileNotFoundError
InterruptedError
IsADirectoryError
NotADirectoryError
PermissionError
ProcessLookupError
TimeoutError
ReferenceError
RuntimeError
NotImplementedError
RecursionError
StopAsyncIteration
StopIteration
SyntaxError
IndentationError
TabError
SystemError
TypeError
ValueError
UnicodeError
UnicodeDecodeError
UnicodeEncodeError
UnicodeTranslateError
Warning
BytesWarning
DeprecationWarning
FutureWarning
ImportWarning
PendingDeprecationWarning
ResourceWarning
RuntimeWarning
SyntaxWarning
UnicodeWarning
UserWarning
GeneratorExit
KeyboardInterrupt
SystemExit
【问题讨论】:
-
... 以及何时处理它们。但请不要使用空白
except,请指定您要捕获的错误。 -
这是一个关于exception handling / 错误处理的非常笼统的问题,对于这种问答格式来说太宽泛了。您可能应该从阅读该主题开始。然后在实践中询问具体案例。
标签: python python-3.x error-handling exception-handling