Python Forum

Full Version: Qt app won't crash after sys.excepthook override
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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()
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.
(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?
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.