我如何编写一个可以捕获所有异常的 try/except 块?
try
except
编写一个try/`except块except子句。这将捕获所有异常,包括系统退出异常,如SystemExit、KeyboardInterrupt和GeneratorExit。但是,通常建议捕获特定异常以避免掩盖您可能需要注意的错误。如果您需要捕获所有异常以进行日志记录或清理,则应考虑在处理捕获的异常后重新引发它们。
`except
SystemExit
KeyboardInterrupt
GeneratorExit
下面是捕获所有异常的try/块的示例:except
try: # Your code here result = 10 / 0 # This will raise a ZeroDivisionError except Exception as e: # Handle the exception print(f"An exception occurred: {e}") # Output: An exception occurred: division by zero
try:
except Exception as e:
Exception
捕获所有异常有时会隐藏应解决的问题。如果您需要执行清理操作或记录异常,您可以考虑以下模式:
try: # Your code here result = 10 / 0 # This will raise a ZeroDivisionError except Exception as e: # Handle the exception (e.g., log it) print(f"An exception occurred: {e}") # Re-raise the exception to ensure it can be handled elsewhere if necessary raise
如果要捕获所有异常,包括SystemExit、KeyboardInterrupt和GeneratorExit,则可以使用裸except:子句。通常不建议这样做,因为它会使您的程序难以调试和维护:
except:
try: # Your code here result = 10 / 0 # This will raise a ZeroDivisionError except: # Handle the exception print("An exception occurred")
try: # Your code here result = 10 / 0 # This will raise a ZeroDivisionError except: # Handle the exception print("An exception occurred") finally: # Cleanup code here print("Cleaning up...") # Output: # An exception occurred # Cleaning up...
finally: