How to catch errors in properties?

I have an object say Bar with property val. If an invalid value is set for val, it raises an Exception. How do I catch the exception in atry ... except block?
Example.

import gi

gi.require_versions({"Adw": "1"})
from gi.repository import Adw, GObject, Gtk


class Bar(GObject.Object):
    _val = ""

    @GObject.Property(type=str)
    def val(self):
        return self._val

    @val.setter
    def val(self, val):
        self._val = val
        raise Exception("Catch me if you can")


def set_x(_, x):
    try:
        print("Setting value")
        x.val = "hello"
        print("Set value")
    except Exception as err:
        print("Caught", err)
    else:
        print("No error")


def on_activate(application):
    win = Adw.ApplicationWindow(application=application)
    x = Bar()
    button = Gtk.Button(label="Cause Error")
    button.connect("clicked", set_x, x)
    win.set_content(button)
    win.present()


app = Adw.Application(application_id="com.example.app")
app.connect("activate", on_activate)
app.run([])

If I run this and click the button, this is the output I get:

$ python3 app.py
Setting value
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/gi/_propertyhelper.py", line 401, in obj_set_property
    prop.fset(self, value)
  File "/home/arun-mani-j/Projects/app.py", line 17, in val
    raise Exception("Catch me if you can")
Exception: Catch me if you can
Set value
No error

Why isn’t the error caught in except?

Yep, that’s a known issue of PyGObject. See:

Note that Issue 6 is not really relevant in this specific case, but would be if the try...except block were on the app.run call.

Wow that’s a 13 year old issue. Though I don’t know how to really fix the issue, I will use some hacks to make the exception occur less :slight_smile: