为什么一个包罗万象的 try: / except: 不足以捕获异常?

Why is a overencompassing try: / except: not enough to catch an exception?

我虽然最外层的 try: / except: 总是会捕获异常(这可能不是一个好主意的事实不在问题范围内):

try:
    try:
        raise ValueError
    except:
        raise ValueError
except:
    pass

some code 中,我遇到了

def process_batch(self):
    try:
        p = util.json_dumps(self.batch_data)
        mac = hmac.new(self.key, p)
        send_bytes = struct.pack('B', mac.digest_size) + mac.digest() + p
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            try:
                s.connect((self.host, self.port))
            except socket.error:
                s.close()
                s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
                s.connect((self.host, self.port))
            s.send(send_bytes)
        finally:
            s.close()
    except Exception:
        self.logger_logger.exception("Failed to send network data")

引发异常:

2019-02-09 23:32:51     INFO (simplemonitor) monitor passed: hass
2019-02-09 23:32:51     INFO (simplemonitor) monitor passed: dns
2019-02-09 23:32:51    ERROR (simplemonitor.logger-send-to-srv) Failed to send network data
Traceback (most recent call last):
  File "/opt/simplemonitor/Loggers/network.py", line 89, in process_batch
    s.connect((self.host, self.port))
ConnectionRefusedError: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/simplemonitor/Loggers/network.py", line 93, in process_batch
    s.connect((self.host, self.port))
socket.gaierror: [Errno -5] No address associated with hostname

为什么会这样?为什么包罗万象的try:/except:没有捕捉到异常?

在提供的第二个代码示例中,Traceback 消息实际上不是未处理的异常,因为异常处理程序调用 logger.exception 方法,它将打印出指定的消息以及完整的Traceback 消息进入日志流。如果不需要 Traceback,使用 logger.error 将在没有它的情况下以相同的 ERROR 级别生成日志消息。