Debian Codegraph @

docs/guide/api/error_handling.rst

raw
1 .. currentmodule:: gi.repository
2
3 ==============
4 Error Handling
5 ==============
6
7 GLib has its own method of handling errors using :obj:`GLib.Error`. These are
8 raised as Python exceptions, but with a few small differences.
9
10 It's common in Python for exception subclasses to be used (e.g.,
11 :obj:`ValueError` versus :obj:`IOError`) to distinguish different types of
12 errors. Libraries often define their own :obj:`Exception` subclasses, and
13 library users will handle these cases explicitly.
14
15 In GLib-using libraries, errors are all :obj:`GLib.Error` instances, with no
16 subclassing for different error types. Instead, every :obj:`GLib.Error`
17 instance has attributes that distinguish types of error:
18
19 * :attr:`GLib.Error.domain` is the error domain, usually a string that you can
20 convert to a ``GLib`` quark with :func:`GLib.quark_from_string`
21 * :attr:`GLib.Error.code` identifies a specific error within the domain
22 * :attr:`GLib.Error.message` is a human-readable description of the error
23
24 Error domains are defined per-module, and you can get an error domain from
25 ``*_error_quark`` functions on the relevant module. For example, IO errors
26 from ``Gio`` are in the domain returned by :func:`Gio.io_error_quark`, and
27 possible error code values are enumerated in :obj:`Gio.IOErrorEnum`.
28
29 Once you've caught a :obj:`GLib.Error`, you can call
30 :meth:`GLib.Error.matches` to see whether it matches the specific error you
31 want to handle.
32
33
34 Examples
35 --------
36
37 Catching a specific error:
38
39 .. code:: pycon
40
41 >>> from gi.repository import GLib, Gio
42 >>> f = Gio.File.new_for_path('missing-path')
43 >>> try:
44 ... f.read()
45 ... except GLib.Error as err:
46 ... if err.matches(Gio.io_error_quark(), Gio.IOErrorEnum.NOT_FOUND):
47 ... print('File not found')
48 ... else:
49 ... raise
50 File not found