valagsettings

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


I am using Glib.Settings in my Vala application. And I want to make sure that my program will work okay even when the schema or key is not available. So I've added a try/catch block, but if I'm using the key that doesn't exist, the program segfaults. As I understood, it doesn't even reach the catch statement. Here is the function that uses settings:

GLib.Settings settings;
string token = "";
try 
{
    settings = new GLib.Settings (my_scheme);
    token = settings.get_string("token1");
}
catch (Error e) 
{
    print("error");
    token = "";
}
return token;

And the program output is:

(main:27194): GLib-GIO-ERROR **: Settings schema 'my_scheme' does not contain a key named 'token1'
Trace/breakpoint trap (core dumped)

(of course I'm using my real scheme string instead of my_scheme) So can you suggest me where I'm wrong?


Solution

  • 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.