0

I have a parent class who has a try clause in it, and a child class overrides a method inside of the try clause. Normal exceptions can be caught when the child raises it. However, the keyboard interrupt exception cannot be caught. Moreover, it can be caught inside the child method, but not the parent method.

Please see the example code like the following, where the interrupt cannot be caught in bar1, but can be caught after bar2 changes it into an assertion error. I produced this problem in python 3.6 in both Linux and Windows.

import time
class foo:
    def body(self):
        pass
    def run(self):
        try:
            self.body()
        except Exception as ex:
            print("caught exception:", str(ex))

class bar1(foo):
    def body(self):
        while(1):
            print(1)
            time.sleep(0.1)

class bar2(foo):
    def body(self):
        interrupted = False
        while(1):
            assert not interrupted, "assert not interrupted"
            try:
                print(1)
                time.sleep(0.1)
            except KeyboardInterrupt as ex:
                print("received interrupt")
                interrupted = True

Interrupting the run method of class bar1 gets

1
....
1
Traceback (most recent call last):
  File "tmp.py", line 34, in <module>
    b.run()
  File "tmp.py", line 7, in run
    self.body()
  File "tmp.py", line 15, in body
    time.sleep(0.1)
KeyboardInterrupt

However, interrupting bar2 gets

1
...
1
received interrupt
caught exception: assert not interrupted

I have searched over StackOverflow and found some problems regarding the keyboard interruption handling with threads and stdIO, but I did not found some problems like this.

martineau
  • 119,623
  • 25
  • 170
  • 301
Yangcy
  • 167
  • 1
  • 6
  • A failed `assert` raises `AssertionError` which is being caught by your `except Excetion as exc` in `foo`. If you don't want that, you should catch only specific exeptions in that catch block – rdas May 08 '20 at 05:00
  • In the example, I compared the `AssertionError` against the `KeyboardInterrupt`. Both of them **should** be caught by `except Excetion as exc`. However, the `KeyboardInterrupt` did not get caught. I use the `AssertionError` here because I want to trigger an exception with`CTRL` + `C`, sorry for the misleading example. – Yangcy May 08 '20 at 08:18

0 Answers0