我想从内部尝试到外部尝试的所有内容打印所有异常语句。有什么办法可以做到而无需更改内部try-catch块

def test_nested_exceptions():
    try:
        try:
            raise AssertionError('inner error ')
        except AssertionError as ae:

            raise AssertionError("error in except")
        finally:
            raise AssertionError("error in finally")
    except AssertionError as e:
        print(e)

最佳答案

您无法访问finally块中的错误对象,但可以使用sys模块获得一些详细信息,如下所示。

import sys

def test_nested_exceptions():
  try:
    try:
      raise AssertionError('inner error ')
    except AssertionError as ae:
      print(ae)
      raise AssertionError("error in except")
    finally:
      print(sys.exc_info())
      raise AssertionError("error in finally")
  except AssertionError as e:
    print(e)


test_nested_exceptions()

10-08 05:53