How to print Exceptions of a nested loop?

127 views Asked by At

I want to print all the exception statements from within the inner try to the catch of the outside try. Is there any way to do this without changing the inner try-catch block

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)
1

There are 1 answers

0
Shane Richards On

You can't access the error object in the finally block but you could get some details using the sys module as shown below.

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()