Python Forum
[PyQt] Qt app won't crash after sys.excepthook override
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyQt] Qt app won't crash after sys.excepthook override
#1
Bug 
As detailed in the docs, all exceptions can be caught by monkey patching sys.excepthook, while __excepthook__ contains the original value. However, when used in some Qt events, altough the error is caught, the app doesn't crash.

In the example below, the app crash when raise is called in __init__, but not in keyPressEvent. The workaround is to call sys.exit(1) after __excepthook__.
But why is it needed? Anyone has an idea?

#!/usr/bin/python3
import sys
from PyQt5 import QtWidgets


class Text(QtWidgets.QPlainTextEdit):
    def __init__(self):
        super().__init__()
        # raise NotImplementedError  # Crash (expected behavior)

    def keyPressEvent(self, event):
        raise NotImplementedError  # Does not crash (unexpected)
        super().keyPressEvent(event)


class Main(QtWidgets.QWidget):
    def __init__(self, parent):
        super().__init__()
        layout = QtWidgets.QVBoxLayout()
        layout.insertWidget(0, Text())
        self.setLayout(layout)
        self.show()


def _exception(type_, value, tb):
    print(f"Caught: {type_} {value}".rstrip())
    sys.__excepthook__(type_, value, tb)
    # sys.exit(1)


sys.excepthook = _exception


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    gui = Main(app)
    app.exec()
Reply
#2
I expect that Qt has an exception handler that catches the exception raised in the keypressEvent(). No such exception handler is ready to catch the exception raised in the __init_() method.

This is exactly the behavior I expect.
Reply
#3
(Dec-27-2020, 09:18 PM)deanhystad Wrote: I expect that Qt has an exception handler that catches the exception raised in the keypressEvent(). No such exception handler is ready to catch the exception raised in the __init_() method.

This is exactly the behavior I expect.

When sys.excepthook is not overridden, an exception in keyPressEvent() exits the app. Why this behavior is not restored once sys.__excepthook__() is called?
Reply
#4
It does not crash when I comment out line 31. I get a trace but the program continues to run. I am using PySide2 though.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] Override the paste function(copy from excel file - paste in separate tkinter entryes) AndreiV 3 4,557 Jun-05-2020, 04:46 PM
Last Post: AndreiV
  [PyQt] timer makes my qmessagebox crash darktitan 17 7,599 Feb-19-2020, 07:11 PM
Last Post: darktitan
  PY TO EXE CRASH kozaizsvemira 0 2,250 Oct-19-2019, 07:27 PM
Last Post: kozaizsvemira

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020