在Python中,即使使用try/except语句捕获异常,程序仍然可能崩溃吗?

huangapple go评论159阅读模式
英文:

Is it possible for program to crash even with try/except statement that captures Exception in Python?

问题

我正在创建一些自动化程序,用于在特定时间重新启动设备。为了在设备重启后重新连接,我希望在等待一段时间后继续尝试连接,直到最终重新连接成功。由于在重新连接失败时会出现错误,我认为我可以捕获所有异常,然后休眠一段时间,然后再次运行连接代码并继续此循环。然而,我的程序在达到连接错误后仍会崩溃。是否有一些异常无法捕获?

这是我创建的函数供参考,但我仍然遇到各种不同的错误,如“requests.exceptions.ConnectionError”、“urllib3.exceptions.MaxRetryError”、“urllib3.exceptions.NewConnectionError”和“ConnectionRefusedError”。

  1. def establish_session(device):
  2. try:
  3. sess = IdentityServicesEngineAPI(username=config.username,
  4. password=config.password,
  5. base_url='https://' + device,
  6. verify=False)
  7. except Exception as e:
  8. print("连接被拒绝。节点正在重新启动。60秒后重试")
  9. time.sleep(60)
  10. return establish_session(device) # 在此嵌套...
  11. return sess

非常感谢您的反馈。

英文:

I am creating some automation that restarts a device at a certain point. In order to reconnect after it reboots, I want to continue to attempt to connect after a wait period until it finally reconnects. Since there will be errors when it fails to reconnect, I thought I could catch all exceptions and then just sleep for some time period and then run the connection code again and continue this loop. However, my program still crashes after it reaches the connection errors. Are there just some exceptions that can not be caught?

This is the function I created for reference and I am still just getting a bunch of different errors like requests.exceptions.ConnectionError, urllib3.exceptions.MaxRetryError, urllib3.exceptions.NewConnectionError, and ConnectionRefusedError

  1. def establish_session(device):
  2. try:
  3. sess = IdentityServicesEngineAPI(username=config.username,
  4. password=config.password,
  5. base_url='https://' + device,
  6. verify=False)
  7. except Exception as e:
  8. print("connection refused. node rebooting. Trying again in 60 seconds")
  9. time.sleep(60)
  10. return establish_session(device) # Nested here...
  11. return sess

Any feedback would be greatly appreciated

Update: adding full traceback.

  1. Traceback (most recent call last):
  2. File "/python3.10/site-packages/urllib3/connection.py", line 174, in _new_conn
  3. conn = connection.create_connection(
  4. File "/python3.10/site-packages/urllib3/util/connection.py", line 95, in create_connection
  5. raise err
  6. File "/python3.10/site-packages/urllib3/util/connection.py", line 85, in create_connection
  7. sock.connect(sa)
  8. ConnectionRefusedError: [Errno 61] Connection refused
  9. During handling of the above exception, another exception occurred:
  10. Traceback (most recent call last):
  11. File "/python3.10/site-packages/urllib3/connectionpool.py", line 714, in urlopen
  12. httplib_response = self._make_request(
  13. File "/python3.10/site-packages/urllib3/connectionpool.py", line 403, in _make_request
  14. self._validate_conn(conn)
  15. File "/python3.10/site-packages/urllib3/connectionpool.py", line 1053, in _validate_conn
  16. conn.connect()
  17. File "/python3.10/site-packages/urllib3/connection.py", line 363, in connect
  18. self.sock = conn = self._new_conn()
  19. File "/python3.10/site-packages/urllib3/connection.py", line 186, in _new_conn
  20. raise NewConnectionError(
  21. urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x104e2b670>: Failed to establish a new connection: [Errno 61] Connection refused
  22. During handling of the above exception, another exception occurred:
  23. Traceback (most recent call last):
  24. File "/python3.10/site-packages/requests/adapters.py", line 486, in send
  25. resp = conn.urlopen(
  26. File "/python3.10/site-packages/urllib3/connectionpool.py", line 798, in urlopen
  27. retries = retries.increment(
  28. File "/python3.10/site-packages/urllib3/util/retry.py", line 592, in increment
  29. raise MaxRetryError(_pool, url, error or ResponseError(cause))
  30. urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='device1', port=443): Max retries exceeded with url: /api/v1/task (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x104e2b670>: Failed to establish a new connection: [Errno 61] Connection refused'))
  31. During handling of the above exception, another exception occurred:
  32. Traceback (most recent call last):
  33. File "/python3.10/site-packages/ciscoisesdk/restsession.py", line 497, in request
  34. response = self._req_session.request(method, abs_url, **kwargs)
  35. File "/python3.10/site-packages/requests/sessions.py", line 589, in request
  36. resp = self.send(prep, **send_kwargs)
  37. File "/python3.10/site-packages/requests/sessions.py", line 703, in send
  38. r = adapter.send(request, **kwargs)
  39. File "/python3.10/site-packages/requests/adapters.py", line 519, in send
  40. raise ConnectionError(e, request=request)
  41. requests.exceptions.ConnectionError: HTTPSConnectionPool(host='device1', port=443): Max retries exceeded with url: /api/v1/task (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x104e2b670>: Failed to establish a new connection: [Errno 61] Connection refused'))
  42. During handling of the above exception, another exception occurred:
  43. Traceback (most recent call last):
  44. File "/python3.10/site-packages/urllib3/connection.py", line 174, in _new_conn
  45. conn = connection.create_connection(
  46. File "/python3.10/site-packages/urllib3/util/connection.py", line 95, in create_connection
  47. raise err
  48. File "/python3.10/site-packages/urllib3/util/connection.py", line 85, in create_connection
  49. sock.connect(sa)
  50. ConnectionRefusedError: [Errno 61] Connection refused
  51. During handling of the above exception, another exception occurred:
  52. Traceback (most recent call last):
  53. File "/python3.10/site-packages/urllib3/connectionpool.py", line 714, in urlopen
  54. httplib_response = self._make_request(
  55. File "/python3.10/site-packages/urllib3/connectionpool.py", line 403, in _make_request
  56. self._validate_conn(conn)
  57. File "/python3.10/site-packages/urllib3/connectionpool.py", line 1053, in _validate_conn
  58. conn.connect()
  59. File "/python3.10/site-packages/urllib3/connection.py", line 363, in connect
  60. self.sock = conn = self._new_conn()
  61. File "/python3.10/site-packages/urllib3/connection.py", line 186, in _new_conn
  62. raise NewConnectionError(
  63. urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x104e29930>: Failed to establish a new connection: [Errno 61] Connection refused
  64. During handling of the above exception, another exception occurred:
  65. Traceback (most recent call last):
  66. File "/lib/python3.10/site-packages/requests/adapters.py", line 486, in send
  67. resp = conn.urlopen(
  68. File "/python3.10/site-packages/urllib3/connectionpool.py", line 798, in urlopen
  69. retries = retries.increment(
  70. File "/python3.10/site-packages/urllib3/util/retry.py", line 592, in increment
  71. raise MaxRetryError(_pool, url, error or ResponseError(cause))
  72. urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='device1', port=443): Max retries exceeded with url: /api/v1/task (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x104e29930>: Failed to establish a new connection: [Errno 61] Connection refused'))
  73. During handling of the above exception, another exception occurred:
  74. Traceback (most recent call last):
  75. File "/lib/python3.10/site-packages/ciscoisesdk/restsession.py", line 504, in request
  76. response = self._req_session.request(method, abs_url,
  77. File "/python3.10/site-packages/requests/sessions.py", line 589, in request
  78. resp = self.send(prep, **send_kwargs)
  79. File "/python3.10/site-packages/requests/sessions.py", line 703, in send
  80. r = adapter.send(request, **kwargs)
  81. File "/python3.10/site-packages/requests/adapters.py", line 519, in send
  82. raise ConnectionError(e, request=request)
  83. requests.exceptions.ConnectionError: HTTPSConnectionPool(host='device1', port=443): Max retries exceeded with url: /api/v1/task (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x104e29930>: Failed to establish a new connection: [Errno 61] Connection refused'))
  84. During handling of the above exception, another exception occurred:
  85. Traceback (most recent call last):
  86. File "/Pre_Post_Checks_Automation/test_api_calls.py", line 5, in <module>
  87. hold = api.tasks.get_task_status().response
  88. File "python3.10/site-packages/ciscoisesdk/api/v3_1_patch_1/tasks.py", line 123, in get_task_status
  89. _api_response = self._session.get(endpoint_full_url, params=_params)
  90. File "/python3.10/site-packages/ciscoisesdk/restsession.py", line 609, in get
  91. response = self.request('GET', url, erc, 0, params=params, **kwargs)
  92. File "python3.10/site-packages/ciscoisesdk/restsession.py", line 507, in request
  93. raise ciscoisesdkException('Socket error {}'.format(e))
  94. ciscoisesdk.exceptions.ciscoisesdkException: Socket error HTTPSConnectionPool(host='device1', port=443): Max retries exceeded with url: /api/v1/task (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x104e29930>: Failed to establish a new connection: [Errno 61] Connection refused'))

答案1

得分: 0

回答标题中的问题,是的,有些异常不是Exception。例如,GeneratorExitKeyboardInterruptSystemExit不是Exception的子类,而是BaseException的子类,这意味着它们不会在except Exception子句中被捕获。

请参考此链接以获取内置异常的层次结构:

https://docs.python.org/3/library/exceptions.html#exception-hierarchy

以及来自mCoding的这个非常有用的视频:

https://www.youtube.com/watch?v=zrVfY9SuO64

英文:

To answer the question in the title, yes, some exceptions are not Exception. For example, GeneratorExit, KeyboardInterrupt and SystemExit are not subclasses of Exception but of BaseException, meaning they won't be caught in the except Exception clause.

See this for a hierarchy of builtin exceptions:

https://docs.python.org/3/library/exceptions.html#exception-hierarchy

as well as this very useful video from mCoding:

https://www.youtube.com/watch?v=zrVfY9SuO64

huangapple
  • 本文由 发表于 2023年6月29日 03:17:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76576116.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定