Friday, 22 October 2021

No exception "bubbling up" from PySide slots

Demo code:

from PySide2.QtCore import Signal
from PySide2.QtWidgets import QApplication, QDialog


class MyDialog(QDialog):

mySignal = Signal()


def mySignal_handler():
raise Exception("bocs")


app = QApplication()
dialog = MyDialog()
dialog.mySignal.connect(mySignal_handler)
dialog.mySignal.connect(mySignal_handler)

try:
dialog.mySignal.emit()
except Exception as ex:
print("It is still the same exception context.")

Now try to guess the output ... :)

Interestingly enough to me, exceptions raised in "signal handlers" (okay, slots, in Qt terminology), will be propagated towards the default exception hook right as they leave the slot's block.

The entity emitting the signal never hears back.

Instead, each slot "defines" its own context - for each "signal subscriber", there will be a corresponding potential of throwing an exception.

I assume this can allow for some degree of robustness in case of user interfaces, in other words it isn't impossible to argue for like approaches, but comes with the drawback of not being able to delegate functionalities via this mechanism if they'd need to "signal back" the interruption of the processing flow via exceptions.

I'll have to default to some observer-pattern-like subscription based design I suppose, watch out for similar situations, re-evaluate my approaches generally ... sounds like great fun : ))

... and indeed, the output was two (independent) exception traces:

Traceback (most recent call last):
File "draft_scripts/qt_signal_exception_context_qt6.py", line 11, in mySignal_handler
raise Exception("bocs")
Exception: bocs
Traceback (most recent call last):
File "draft_scripts/qt_signal_exception_context_qt6.py", line 11, in mySignal_handler
raise Exception("bocs")
Exception: bocs

A bit of a shame I don't have the capacity to migrate to PySide6, so it's affecting me with PySide2, but as far as I could confirm that by a very quick test run, the problem (? - seems pretty much an intended behaviour, maybe not for the Py... Qt wrappers, but at the heart of Qt) equally manifests in both versions.

No comments:

Post a Comment