我该如何编写一个能够捕获所有异常的 try
/except
块?
除了一个裸露的 except:
从句(正如其他人所说,你不应该使用),你可以简单地捕获 Exception
:
import traceback
import logging
try:
whatever()
except Exception as e:
logging.error(traceback.format_exc())
# Logs the error appropriately.
如果您想在终止之前处理任何未捕获的异常,通常只会在代码最外层考虑这样做。
except Exception
相对于裸的 except
的优势在于它不会捕获一些异常,其中最明显的是 KeyboardInterrupt
和 SystemExit
:如果您捕获并忽略了它们,那么可能会使其他人难以退出您的脚本。
TypeError
。 - Duncansys.exit()
通常意味着你希望应用程序终止,但如果你捕获了 SystemExit,它就不会终止。同样地,如果你在运行脚本时按下 control-C(Windows 上的 Ctrl-break),你期望程序停止,而不是捕获错误并继续执行。但如果你想在退出之前进行清理,你可以捕获其中任何一个或两个。 - Duncanexcept BaseException as e: notify_user(e); raise
这样就能捕获所有异常并进行任何所需的通知,但我不了解HPC,所以你可能需要发布一个新的SO问题来询问。 - Duncan你可以这样做,但最好不要:
try:
do_something()
except:
print("Caught it!")
不过,这也会捕获像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
except Exception:
。 - Pedro Gordotry:
something()
except BaseException as error:
print('An exception occurred: {}'.format(error))
except:
会捕获到吗?但是它没有给我e
的句柄:( - Charlie ParkerSIGINT
的默认信号处理程序,最开始会引发 KeyboardInterrupt
。当然,你可以捕获 KeyboardInterrupt
,但这只是许多可能过早终止程序的信号之一。其中一些不会生成任何类型的异常,因此最好统一处理所有信号。 - chepnerBaseException
通常不是您想要的。 您真的想捕获键盘中断和sys.exit吗?很可能不是!所有用户定义的异常都应该继承自“Exception”。“查看异常类层次结构。https://dotnettutorials.net/wp-content/uploads/2020/07/word-image-181.png - John Henckel你可以使用这种方法来处理一般性异常
try:
a = 2/0
except Exception as e:
print e.__doc__
print e.message
message
属性。 - nullablehttp://docs.python.org/tutorial/errors.html#defining-clean-up-actions
如果你想捕获所有异常,那么将所有代码放在"try:"语句中,替换掉'print "Performing an action which may throw an exception."'。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."
except:
可以捕获吗?但它不会给我e
的句柄 :( - Charlie Parkerexcept Exception as error:
-- 如果你正在运行Python3。 - Joshua Burns使用Python 3.0及以上版本,有多种方法可以实现这一点。
方法1
这是一种简单的方法,但不推荐使用,因为您无法确定到底是哪一行代码引发了异常:
def bad_method():
try:
sqrt = 0**-1
except Exception as e:
print(e)
bad_method()
方法二
建议采用此方法,因为它提供了有关每个异常更多的详细信息。 它包括:
唯一的缺点是需要导入traceback。
import traceback
def bad_method():
try:
sqrt = 0**-1
except Exception:
print(traceback.print_exc())
bad_method()
except:
会捕获吗? 但它并没有给我一个e
的处理方式 :( - Charlie Parkertraceback.print_exc()
是否可以连接起来? - Unknow0059我刚刚发现了一个在 Python 2.7 中测试异常名称的小技巧。有时候我在代码中处理特定的异常,所以我需要一个测试来确定该名称是否在已处理的异常列表中。
try:
raise IndexError #as test error
except Exception as e:
excepName = type(e).__name__ # returns the name of the exception
except:
会捕获到吗?但是它没有给我e
的句柄:( - Charlie Parker我正在添加一个额外的方法,它可以捕获完整的异常轨迹信息,这可以帮助您更好地理解错误。
Python 3
import traceback
try:
# your code goes here
except Exception as e:
print(e)
traceback.print_exc()
try:
whatever()
except:
# this will catch any exception or error
首先,有些异常情况是希望它们打破你的代码(因为当这种错误发生时,你的代码无法正常运行!),而有些异常情况则需要你平稳地捕获。尝试区分它们。你可能不想捕获所有的异常!
其次,你可以花时间去查看你的进程日志,而不是捕获所有异常。假设你正在遇到不同/第三方异常,比如来自像GCP这样的云服务提供商。在日志中,你可以找到你遇到的异常。然后,你可以做类似这样的事情:
from google.api_core.exceptions import ServiceUnavailable, RetryError
for i in range(10):
try:
print("do something")
except ValueError:
print("I know this might happen for now at times! skipping this and continuing with my loop"
except ServiceUnavailable:
print("our connection to a service (e.g. logging) of gcp has failed")
print("initializing the cloud logger again and try continuing ...")
except RetryError:
print("gcp connection retry failed. breaking the loop. try again later!)
break
对于其余可能发生或不发生的错误,我会留出空间,以便在遇到意外异常时让我的代码崩溃!这样,我就可以了解正在发生的情况,并通过捕获边缘情况来改进我的代码。
如果您希望由于某种原因永远不崩溃,例如它是嵌入到远程硬件中的代码,您无法轻松访问,那么您可以在结尾处添加一个通用异常处理程序:
except Exception as e:
print(f"something went wrong! - {e}")
sys.stderr
并可能被记录。这是一种完全有效和常见的异常处理方式。 - Evgeni Sergeevtry: whatever() except Exception as e: exp_capture()
? - Charlie Parkerexcept: pass
为什么是不良的编程实践? - tripleee