python - 为什么是一个包罗万象的尝试 :/except: not enough to catch an exception?

标签 python python-3.x 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 级别生成日志消息。

关于python - 为什么是一个包罗万象的尝试 :/except: not enough to catch an exception?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54611828/

相关文章:

python - 如何防止用户在Python/Pygame中点击

python - 做一个 ONE :ONE relation on google app engine datastore 最有效的方法是什么

python - 标识符规范化 : Why is the micro sign converted into the Greek letter mu?

Java异常: unknown protocol: udp

java - 声明方法抛出未经检查的异常是否有优势?

c# - 防止将特定异常记录到 App Insights

python - 无法使用 np.where() 在复杂的 2D Python 数组中查找元素的索引

python - 从键列表中获取 Python 字典中的值

python - Python 3.5 中的类型提示是什么?

python - 使用数据框中的两列组合创建字典列,然后计算具有公共(public)键的两列值的比率