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

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

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”。

def establish_session(device):
    try:
        sess = IdentityServicesEngineAPI(username=config.username,
                                         password=config.password,
                                         base_url='https://' + device,
                                         verify=False)
    except Exception as e:
        print("连接被拒绝。节点正在重新启动。60秒后重试")
        time.sleep(60)
        return establish_session(device)  # 在此嵌套...
    
    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

def establish_session(device):
    try:
        sess = IdentityServicesEngineAPI(username=config.username,
                                    password=config.password,
                                    base_url='https://' + device,
                                    verify=False)
    except Exception as e:
        print("connection refused. node rebooting. Trying again in 60 seconds")
        time.sleep(60)
        return establish_session(device) # Nested here...

    return sess

Any feedback would be greatly appreciated

Update: adding full traceback.

Traceback (most recent call last):
  File "/python3.10/site-packages/urllib3/connection.py", line 174, in _new_conn
    conn = connection.create_connection(
  File "/python3.10/site-packages/urllib3/util/connection.py", line 95, in create_connection
    raise err
  File "/python3.10/site-packages/urllib3/util/connection.py", line 85, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 61] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/python3.10/site-packages/urllib3/connectionpool.py", line 714, in urlopen
    httplib_response = self._make_request(
  File "/python3.10/site-packages/urllib3/connectionpool.py", line 403, in _make_request
    self._validate_conn(conn)
  File "/python3.10/site-packages/urllib3/connectionpool.py", line 1053, in _validate_conn
    conn.connect()
  File "/python3.10/site-packages/urllib3/connection.py", line 363, in connect
    self.sock = conn = self._new_conn()
  File "/python3.10/site-packages/urllib3/connection.py", line 186, in _new_conn
    raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x104e2b670>: Failed to establish a new connection: [Errno 61] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/python3.10/site-packages/requests/adapters.py", line 486, in send
    resp = conn.urlopen(
  File "/python3.10/site-packages/urllib3/connectionpool.py", line 798, in urlopen
    retries = retries.increment(
  File "/python3.10/site-packages/urllib3/util/retry.py", line 592, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
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'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/python3.10/site-packages/ciscoisesdk/restsession.py", line 497, in request
    response = self._req_session.request(method, abs_url, **kwargs)
  File "/python3.10/site-packages/requests/sessions.py", line 589, in request
    resp = self.send(prep, **send_kwargs)
  File "/python3.10/site-packages/requests/sessions.py", line 703, in send
    r = adapter.send(request, **kwargs)
  File "/python3.10/site-packages/requests/adapters.py", line 519, in send
    raise ConnectionError(e, request=request)
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'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/python3.10/site-packages/urllib3/connection.py", line 174, in _new_conn
    conn = connection.create_connection(
  File "/python3.10/site-packages/urllib3/util/connection.py", line 95, in create_connection
    raise err
  File "/python3.10/site-packages/urllib3/util/connection.py", line 85, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 61] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/python3.10/site-packages/urllib3/connectionpool.py", line 714, in urlopen
    httplib_response = self._make_request(
  File "/python3.10/site-packages/urllib3/connectionpool.py", line 403, in _make_request
    self._validate_conn(conn)
  File "/python3.10/site-packages/urllib3/connectionpool.py", line 1053, in _validate_conn
    conn.connect()
  File "/python3.10/site-packages/urllib3/connection.py", line 363, in connect
    self.sock = conn = self._new_conn()
  File "/python3.10/site-packages/urllib3/connection.py", line 186, in _new_conn
    raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x104e29930>: Failed to establish a new connection: [Errno 61] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/lib/python3.10/site-packages/requests/adapters.py", line 486, in send
    resp = conn.urlopen(
  File "/python3.10/site-packages/urllib3/connectionpool.py", line 798, in urlopen
    retries = retries.increment(
  File "/python3.10/site-packages/urllib3/util/retry.py", line 592, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
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'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/lib/python3.10/site-packages/ciscoisesdk/restsession.py", line 504, in request
    response = self._req_session.request(method, abs_url,
  File "/python3.10/site-packages/requests/sessions.py", line 589, in request
    resp = self.send(prep, **send_kwargs)
  File "/python3.10/site-packages/requests/sessions.py", line 703, in send
    r = adapter.send(request, **kwargs)
  File "/python3.10/site-packages/requests/adapters.py", line 519, in send
    raise ConnectionError(e, request=request)
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'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Pre_Post_Checks_Automation/test_api_calls.py", line 5, in <module>
    hold = api.tasks.get_task_status().response
  File "python3.10/site-packages/ciscoisesdk/api/v3_1_patch_1/tasks.py", line 123, in get_task_status
    _api_response = self._session.get(endpoint_full_url, params=_params)
  File "/python3.10/site-packages/ciscoisesdk/restsession.py", line 609, in get
    response = self.request('GET', url, erc, 0, params=params, **kwargs)
  File "python3.10/site-packages/ciscoisesdk/restsession.py", line 507, in request
    raise ciscoisesdkException('Socket error {}'.format(e))
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:

确定