How to handle errors while using Glib.Settings in Vala?

◇◆丶佛笑我妖孽 提交于 2019-12-05 17:27:00

The methods in GLib.Settings, including get_string do not throw exceptions, they call abort inside the library. This is not an ideal design, but there isn't anything you can do about it.

In this case, the correct thing to do is fix your schema, install into /usr/share/glib-2.0/schemas and run glib-compile-schemas on that directory (as root).

Vala only has checked exceptions, so, unlike C#, a method must declare that it will throw, or it is not possible to do so. You can always double check the Valadoc or the VAPI to see.

I know this is super late, but I was looking for the same solution so I thought I'd share one. As @apmasell said, the GLib.Settings methods don't throw exceptions—they just abort instead.

However, you can do a SettingsSchemaSource.lookup to make sure the key exists first. You can then also use has_key for specific keys. For example,

var settings_schema = SettingsSchemaSource.get_default ().lookup ("my_scheme", false);
if (settings_schema != null) {
    if (settings_schema.has_key ("token1")) {
        var settings = new GLib.Settings ("my_scheme");
        token = settings.get_string("token1");
    } else {
        critical ("Key does not exist");
    }
} else {
    critical ("Schema does not exist");
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!