Skip to content

Exceptions in callbacks

Matijs van Zuijlen edited this page Dec 11, 2015 · 3 revisions

Note: Support for automatically breaking out of the event loop on exceptions has been added to this gem in master and should be part of the 0.9.0 release.

If callbacks are run from a separate C thread, any exceptions raised will not be propagated to Ruby. Therefore, it may seem the callbacks are just not doing anything. In such cases, it is helpful to add an exception handler inside the callback, even just to print the exception. Note that this is is a special case, and exceptions will mostly be propagated up to the Ruby method triggering the callback.

Here is an example taken from issue #10 in GirFFI-Gtk:

require 'gir_ffi-gtk3'

Gtk.init

draw_area = Gtk::DrawingArea.new
GObject.signal_connect(draw_area, "draw") do |widget, ctx|
  begin
    width = widget.get_allocated_width
    height = widget.get_allocated_height
    ctx.arc(width / 2.0, height / 2.0, [width, height].min / 2.0, 0, 2 * Math::PI)
    ctx.set_source_rbga(1, 1, 0, 0.5)
    ctx.fill
  rescue => e
    puts e
  end
  false
end

draw_area.set_size_request(100, 100)

win = Gtk::Window.new :toplevel
win.add(draw_area)
win.show_all
GObject.signal_connect(win, "destroy") { Gtk.main_quit }

Gtk.main

See also issue #141 in FFI,and issue #40 in GirFFI.

Adding Thread.abort_on_exception has no effect.

Clone this wiki locally