Search code examples
rubyexceptionunhandled-exception

Unhandled Exceptions in Ruby


I am working on a ruby project for the first time. I've got everything I need working except I want to be able to register an unhandled exception handler so I can trigger something if a crash occurs that isn't handled by a rescue but I can't see if that's possible.

I've done with lots of other languages like in Python I've done the following:

sys.excepthook = MyClass._unhandledCrashHandler

I can't find any equivalent to do this in Ruby. Is this possible?

Should have mentioned, I'm writing a Ruby library, so the idea is when the main ruby app initialises my library, the library sets up the handled exception handler and then if the main app crashes, the library gets the crash. This is what I've done in python and many other languages without issue but can't see any way of doing this in Ruby.


Solution

  • Ruby doesn't have generic handlers, but instead you wrap the code which might generate exceptions. For example:

    begin
      # ... Do stuff
    rescue => e
      $stderr.puts("[%s] %s" % [ e.class, e ])
      $stderr.puts(e.backtrace.join("\n"))
    end
    

    Where that rescues all standard exceptions and displays some diagnostic output. You can do whatever you want in the rescue block. Any uncaught exceptions will bubble up to your top-level automatically.

    This must be the top-level code for your Ruby application.

    The closest thing to what you're talking about in Ruby is the at_exit handler you can define, but this runs in every exit scenario (except terminating the program with exit!) not just uncaught exceptions.