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?

import gi

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

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

    def val(self):
        return self._val

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

def set_x(_, x):
        print("Setting value")
        x.val = "hello"
        print("Set value")
    except Exception as err:
        print("Caught", err)
        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)

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

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

$ python3
Setting value
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/gi/", line 401, in obj_set_property
    prop.fset(self, value)
  File "/home/arun-mani-j/Projects/", 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 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:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.