# Abstracting exception handling

**URL:** <https://rubytalk.org/t/abstracting-exception-handling/59503>\
**Category:** ruby-talk\
**Created:** [5 August 2010 10:06 UTC](https://rubytalk.org/t/abstracting-exception-handling/59503 "2010-08-05T10:06:05Z")\
**Posts on this page:** 15\
**Page:** 1

<div class="post-metadata">

**Author:** ![Martin\_Hansen](https://avatars.discourse-cdn.com/v4/letter/m/e36b37/32.png) [@Martin\_Hansen](https://rubytalk.org/u/Martin_Hansen)\
**Post date:** [5 August 2010 10:06 UTC](https://rubytalk.org/t/abstracting-exception-handling/59503/1 "2010-08-05T10:06:05Z")

</div>

Hello,

I am interested in abstracting exception handling so it can be included  
to any script from some external file. First, I want to setup signal  
handling, and last I want to deal with exceptions. Now, in this little  
test of mine something is bad, since the exception is not caught. I  
suspect something is going out of scope and lost?

Martin

#!/usr/bin/env ruby

def do\_at\_begin  
&nbsp;&nbsp;exit\_status = "OK"

&nbsp;&nbsp;# Install signal handlers  
&nbsp;&nbsp;%w( INT TERM QUIT ).each do |signal|  
&nbsp;&nbsp;&nbsp;&nbsp;Signal.trap(signal) do  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;exit\_status = signal  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;exit  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;end

&nbsp;&nbsp;exit\_status  
end

def do\_at\_exit(exit\_status="OK-default")  
&nbsp;&nbsp;begin  
&nbsp;&nbsp;rescue Exception =\> exception  
&nbsp;&nbsp;&nbsp;&nbsp;$stderr.puts "Exception caught!"  
&nbsp;&nbsp;&nbsp;&nbsp;$stderr.puts exit\_status  
&nbsp;&nbsp;&nbsp;&nbsp;$stderr.puts exception.backtrace  
&nbsp;&nbsp;ensure  
&nbsp;&nbsp;&nbsp;&nbsp;puts "DEBUG EXIT STATUS: #{exit\_status}"  
&nbsp;&nbsp;end  
end

exit\_status = do\_at\_begin

raise

END {  
&nbsp;&nbsp;do\_at\_exit(exit\_status)  
}

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Brian\_Candler](https://avatars.discourse-cdn.com/v4/letter/b/5f9b8f/32.png) [@Brian\_Candler](https://rubytalk.org/u/Brian_Candler)\
**Post date:** [5 August 2010 13:29 UTC](https://rubytalk.org/t/abstracting-exception-handling/59503/2 "2010-08-05T13:29:09Z")

</div>

> I suspect something is going out of scope and lost?

Nope. The exception is raised, nothing catches it, \*then\* your END block  
is executed. You can only catch exceptions which are raised after the  
'begin' of the exception block.

Depending on what you're trying to do, the at\_exit function might help  
you. Otherwise, you need to restructure your code like this:

begin  
&nbsp;&nbsp;run\_my\_program  
rescue Exception  
&nbsp;&nbsp;puts "I got #{$!}"  
end

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Martin\_Hansen](https://avatars.discourse-cdn.com/v4/letter/m/e36b37/32.png) [@Martin\_Hansen](https://rubytalk.org/u/Martin_Hansen)\
**Post date:** [5 August 2010 13:51 UTC](https://rubytalk.org/t/abstracting-exception-handling/59503/3 "2010-08-05T13:51:03Z")

</div>

I was hoping for a setup like this in two files:

my\_script.rb:

include "my\_class"

\<do\_stuff\> or raise

\_\_END\_\_

my\_class.rb:

def do\_at\_begin  
&nbsp;&nbsp;set trap for signals.  
&nbsp;&nbsp;status  
end

def do\_at\_exit  
&nbsp;&nbsp;begin  
&nbsp;&nbsp;rescue Exception  
&nbsp;&nbsp;ensure  
&nbsp;&nbsp;&nbsp;&nbsp;p status  
&nbsp;&nbsp;end  
end

status = do\_at\_begin

END {  
&nbsp;&nbsp;do\_at\_exit(status)  
}

\_\_END\_\_

I want to keep the my\_script.rb file minimal and hence move the error  
handling to the included file. I have no idea if this can be done?

Martin

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Andrew\_Wagner](https://avatars.discourse-cdn.com/v4/letter/a/22d042/32.png) [@Andrew\_Wagner](https://rubytalk.org/u/Andrew_Wagner)\
**Post date:** [5 August 2010 14:02 UTC](https://rubytalk.org/t/abstracting-exception-handling/59503/4 "2010-08-05T14:02:41Z")

</div>

What kind of stuff are you doing in my\_script.rb? Defining a class? A  
method? Several methods? Just evaluating code? You might be able to use hook  
methods to wrap new code that gets defined, but you're being pretty vague  
right now.

> **···**
>
> On Thu, Aug 5, 2010 at 9:51 AM, Martin Hansen \<mail@maasha.dk\> wrote:
> 
> > I was hoping for a setup like this in two files:
> > 
> > my\_script.rb:
> > 
> > include "my\_class"
> > 
> > \<do\_stuff\> or raise
> > 
> > \_\_END\_\_
> > 
> > my\_class.rb:
> > 
> > def do\_at\_begin  
> > set trap for signals.  
> > &nbsp;&nbsp;status  
> > end
> > 
> > def do\_at\_exit  
> > &nbsp;&nbsp;begin  
> > rescue Exception  
> > ensure  
> > &nbsp;&nbsp;&nbsp;p status  
> > end  
> > end
> > 
> > status = do\_at\_begin
> > 
> > END {  
> > do\_at\_exit(status)  
> > }
> > 
> > \_\_END\_\_
> > 
> > I want to keep the my\_script.rb file minimal and hence move the error  
> > handling to the included file. I have no idea if this can be done?
> > 
> > Martin  
> > --  
> > Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Martin\_Hansen](https://avatars.discourse-cdn.com/v4/letter/m/e36b37/32.png) [@Martin\_Hansen](https://rubytalk.org/u/Martin_Hansen)\
**Post date:** [5 August 2010 14:55 UTC](https://rubytalk.org/t/abstracting-exception-handling/59503/5 "2010-08-05T14:55:01Z")

</div>

Andrew Wagner wrote:

> What kind of stuff are you doing in my\_script.rb? Defining a class? A  
> method? Several methods? Just evaluating code?

\<do\_stuff\> would be something simple like parsing a tabular file and  
raising an error if the format is wrong.

Cheers,

Martin

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Andrew\_Wagner](https://avatars.discourse-cdn.com/v4/letter/a/22d042/32.png) [@Andrew\_Wagner](https://rubytalk.org/u/Andrew_Wagner)\
**Post date:** [5 August 2010 16:18 UTC](https://rubytalk.org/t/abstracting-exception-handling/59503/6 "2010-08-05T16:18:52Z")

</div>

So if the do\_stuff is in a format like this:

def do\_something  
.  
.  
.  
end

do\_something

Then when you could do is have a module which overrides Ruby's method that  
gets called when you define a method. You can alias the method being created  
to something else, then define a new method which calls that one, but wraps  
it in whatever error-handling code you want.

> **···**
>
> On Thu, Aug 5, 2010 at 10:55 AM, Martin Hansen \<mail@maasha.dk\> wrote:
> 
> > Andrew Wagner wrote:  
> > \> What kind of stuff are you doing in my\_script.rb? Defining a class? A  
> > \> method? Several methods? Just evaluating code?
> > 
> > \<do\_stuff\> would be something simple like parsing a tabular file and  
> > raising an error if the format is wrong.
> > 
> > Cheers,
> > 
> > Martin  
> > --  
> > Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Martin\_Hansen](https://avatars.discourse-cdn.com/v4/letter/m/e36b37/32.png) [@Martin\_Hansen](https://rubytalk.org/u/Martin_Hansen)\
**Post date:** [5 August 2010 17:37 UTC](https://rubytalk.org/t/abstracting-exception-handling/59503/7 "2010-08-05T17:37:31Z")

</div>

Andrew Wagner wrote:

> Then when you could do is have a module which overrides Ruby's method  
> that  
> gets called when you define a method. You can alias the method being  
> created  
> to something else, then define a new method which calls that one, but  
> wraps  
> it in whatever error-handling code you want.

Sorry, I have no idea how to do that - it sounds terribly complicated.  
Is there no simple solution? Could you perhaps give a small example?

Martin

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Andrew\_Wagner](https://avatars.discourse-cdn.com/v4/letter/a/22d042/32.png) [@Andrew\_Wagner](https://rubytalk.org/u/Andrew_Wagner)\
**Post date:** [5 August 2010 21:13 UTC](https://rubytalk.org/t/abstracting-exception-handling/59503/8 "2010-08-05T21:13:14Z")

</div>

Ok, so here's something fairly simple to try. There are better ways to do  
this, but this should work. In your error-handling file, put this:

module ErrorHandling  
&nbsp;&nbsp;def self.included(cls)  
&nbsp;&nbsp;&nbsp;&nbsp;def cls.method\_added(method)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return if @\_adding\_a\_method  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@\_adding\_a\_method = true

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;original\_method = "original #{method}"  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;alias\_method original\_method, method

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;define\_method(method) do |\*args|  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;begin  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;puts "gonna try something dangerous"  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;send original\_method, \*args  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;rescue Exception  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ensure  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;puts "My last will and testament..."  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@\_adding\_a\_method = false  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;end  
end

The idea is, when you include this module, then it watches for any new  
methods you define. When you define one, it immediately hides it away, and  
creates a new method, which calls the original one, but inside a  
begin/rescue/ensure block. The @\_adding\_a\_method flag is just to keep from  
infinite recursion when you create the new method (because it will also  
trigger method\_added.

Now in your main class, do something like this:

include ErrorHandling

def do\_something  
&nbsp;&nbsp;puts "do something dangerous"  
end

do\_something

> **···**
>
> On Thu, Aug 5, 2010 at 1:37 PM, Martin Hansen \<mail@maasha.dk\> wrote:
> 
> > Andrew Wagner wrote:
> > 
> > \> Then when you could do is have a module which overrides Ruby's method  
> > \> that  
> > \> gets called when you define a method. You can alias the method being  
> > \> created  
> > \> to something else, then define a new method which calls that one, but  
> > \> wraps  
> > \> it in whatever error-handling code you want.
> > 
> > Sorry, I have no idea how to do that - it sounds terribly complicated.  
> > Is there no simple solution? Could you perhaps give a small example?
> > 
> > Martin  
> > --  
> > Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Andrew\_Wagner](https://avatars.discourse-cdn.com/v4/letter/a/22d042/32.png) [@Andrew\_Wagner](https://rubytalk.org/u/Andrew_Wagner)\
**Post date:** [5 August 2010 21:53 UTC](https://rubytalk.org/t/abstracting-exception-handling/59503/9 "2010-08-05T21:53:04Z")

</div>

For a somewhat more robust ErrorHandling module, which requires 1.9, try the  
code below. I should also give credit to the ruby metaprogramming  
screencast\<[http://pragprog.com/screencasts/v-dtrubyom/the-ruby-object-model-and-metaprogramming&gt](http://pragprog.com/screencasts/v-dtrubyom/the-ruby-object-model-and-metaprogramming&gt);  
for  
inspiration for this code. It's practically ripped straight out of there,  
except theirs does tracing, as opposed to just error-handling.

module ErrorHandling  
&nbsp;&nbsp;def self.included(klass)  
&nbsp;&nbsp;&nbsp;&nbsp;klass.instance\_methods(false).each do |existing\_method|  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;wrap(klass, existing\_method)  
&nbsp;&nbsp;&nbsp;&nbsp;end

&nbsp;&nbsp;&nbsp;&nbsp;def klass.method\_added(method)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;unless @watch\_calls\_internal  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@watch\_calls\_internal = true  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ErrorHandling.wrap(self, method)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@watch\_calls\_internal = false  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;end

&nbsp;&nbsp;def self.wrap(klass, method)  
&nbsp;&nbsp;&nbsp;&nbsp;klass.class\_eval do  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;name = method.to\_s  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;original\_method = instance\_method(name)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;define\_method(name) do |\*args, &block|  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;begin  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;puts "attempting..."  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result = original\_method.bind(self).call(\*args, &block)  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;rescue Exception  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ensure  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;puts "last will..."  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;end  
end

> **···**
>
> On Thu, Aug 5, 2010 at 5:13 PM, Andrew Wagner \<wagner.andrew@gmail.com\>wrote:
> 
> > Ok, so here's something fairly simple to try. There are better ways to do  
> > this, but this should work. In your error-handling file, put this:
> > 
> > module ErrorHandling  
> > def self.included(cls)  
> > &nbsp;&nbsp;&nbsp;def cls.method\_added(method)  
> > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return if @\_adding\_a\_method  
> > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@\_adding\_a\_method = true
> > 
> > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;original\_method = "original #{method}"  
> > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;alias\_method original\_method, method
> > 
> > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;define\_method(method) do |\*args|  
> > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;begin  
> > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;puts "gonna try something dangerous"  
> > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;send original\_method, \*args  
> > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;rescue Exception  
> > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ensure  
> > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;puts "My last will and testament..."  
> > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end  
> > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end
> > 
> > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@\_adding\_a\_method = false  
> > &nbsp;&nbsp;&nbsp;end  
> > end  
> > end
> > 
> > The idea is, when you include this module, then it watches for any new  
> > methods you define. When you define one, it immediately hides it away, and  
> > creates a new method, which calls the original one, but inside a  
> > begin/rescue/ensure block. The @\_adding\_a\_method flag is just to keep from  
> > infinite recursion when you create the new method (because it will also  
> > trigger method\_added.
> > 
> > Now in your main class, do something like this:
> > 
> > include ErrorHandling
> > 
> > def do\_something  
> > puts "do something dangerous"  
> > end
> > 
> > do\_something
> > 
> > On Thu, Aug 5, 2010 at 1:37 PM, Martin Hansen \<mail@maasha.dk\> wrote:
> > 
> > \> Andrew Wagner wrote:  
> > \>  
> > \> \> Then when you could do is have a module which overrides Ruby's method  
> > \> \> that  
> > \> \> gets called when you define a method. You can alias the method being  
> > \> \> created  
> > \> \> to something else, then define a new method which calls that one, but  
> > \> \> wraps  
> > \> \> it in whatever error-handling code you want.  
> > \>  
> > \> Sorry, I have no idea how to do that - it sounds terribly complicated.  
> > \> Is there no simple solution? Could you perhaps give a small example?  
> > \>  
> > \>  
> > \> Martin  
> > \> --  
> > \> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).  
> > \>  
> > \>

---

<div class="post-metadata">

**Author:** ![Martin\_Hansen](https://avatars.discourse-cdn.com/v4/letter/m/e36b37/32.png) [@Martin\_Hansen](https://rubytalk.org/u/Martin_Hansen)\
**Post date:** [6 August 2010 08:26 UTC](https://rubytalk.org/t/abstracting-exception-handling/59503/10 "2010-08-06T08:26:55Z")

</div>

I have been looking at your suggestions and done a few tests. However, I  
wonder if there is not a more simple way - and especially since these  
suggestions depends on methods being defined in order to invoke error  
handling. Here is a real life example of the type of minimalistic  
scripts I want to write:

#!/usr/bin/env ruby

require 'biopieces'

casts = []  
casts \<\<  
{:long=\>'compress',:short=\>'Z',:type=\>'flag',:mandatory=\>false,:default=\>nil,:allowed=\>nil,:disallowed=\>nil}

bp = Biopieces.new

options = bp.parse(ARGV,casts)

bp.mktmpdir # create an optional temporary directory that is auto  
deleted.

bp.each\_record do |record|  
&nbsp;&nbsp;# do something to each record (possibly according to the options).  
e.g.:  
&nbsp;&nbsp;record["SEQ"].upcase! if record.has\_key? "SEQ"  
&nbsp;&nbsp;bp.puts record  
&nbsp;&nbsp;raise # Debug test of invokation of error handling  
end

Now, I would like error handling to be invoked, if possible from  
biopieces.rb, in the case some exception is raised (either by raise or  
ctrl-c, etc), but I am not defining any methods and thus the suggested  
meta-programming approaches seem to fall short.

Cheers,

Martin

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Brian\_Candler](https://avatars.discourse-cdn.com/v4/letter/b/5f9b8f/32.png) [@Brian\_Candler](https://rubytalk.org/u/Brian_Candler)\
**Post date:** [6 August 2010 08:39 UTC](https://rubytalk.org/t/abstracting-exception-handling/59503/11 "2010-08-06T08:39:42Z")

</div>

Martin Hansen wrote:

> Now, I would like error handling to be invoked, if possible from  
> biopieces.rb, in the case some exception is raised (either by raise or  
> ctrl-c, etc)

What do you want the exception handler to do? Will the program still  
terminate afterwards?

If so, why not just add an at\_exit handler?

--- prog1.rb ---  
at\_exit { puts "Last exception was #{$!.inspect}" if $! }  
raise "Boom"

--- prog2.rb ---  
at\_exit { puts "Last exception was #{$!.inspect}" if $! }  
puts "Nothing happened"

--- prog3.rb ---  
at\_exit { puts "Last exception was #{$!.inspect}" if $! }  
begin  
&nbsp;&nbsp;raise "Caught it"  
rescue RuntimeError  
end  
puts "Nothing happened"

--- prog4.rb ---  
at\_exit { puts "Last exception was #{$!.inspect}" if $! }  
begin  
&nbsp;&nbsp;raise "Caught it"  
rescue RuntimeError  
end  
sleep 10  
puts "Nothing happened"

Note that both prog2 and prog3 terminate successfully and don't report  
any exception. prog4 reports Interrupt if you terminate with ^C.

Your at\_exit code can of course sit in a separate source file that you  
require.

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Martin\_Hansen](https://avatars.discourse-cdn.com/v4/letter/m/e36b37/32.png) [@Martin\_Hansen](https://rubytalk.org/u/Martin_Hansen)\
**Post date:** [6 August 2010 09:58 UTC](https://rubytalk.org/t/abstracting-exception-handling/59503/12 "2010-08-06T09:58:45Z")

</div>

> What do you want the exception handler to do? Will the program still  
> terminate afterwards?

I want to write the exception type to a log file and terminate the  
script. $! does not tell the difference between interrupt, terminate,  
and quit (perhaps that could be fixed? - just a thought).

> If so, why not just add an at\_exit handler?

I have been messing around with this for a while, but I have failed to  
get it right - and now I am utterly confused.

If I have test.rb:

#!/usr/bin/env ruby

require 'my\_aux\_class'

Greet.new

raise "raise from main"

And my\_aux\_class.rb:

class Greet  
&nbsp;&nbsp;def initialize  
&nbsp;&nbsp;&nbsp;&nbsp;puts "Hello World"  
&nbsp;&nbsp;end  
end

at\_exit {  
&nbsp;&nbsp;puts "Last exception was #{$!.inspect}" if $!  
}

begin  
&nbsp;&nbsp;exit\_status = "OK"

&nbsp;&nbsp;%w( INT TERM QUIT ).each do |signal|  
&nbsp;&nbsp;&nbsp;&nbsp;Signal.trap(signal) do  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;exit\_status = signal  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;exit  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;end

&nbsp;&nbsp;raise "raise from aux"  
rescue Exception =\> exception  
&nbsp;&nbsp;puts "rescuing #{exception}"  
&nbsp;&nbsp;puts exception.backtrace  
ensure  
&nbsp;&nbsp;puts "exit status: #{exit\_status}"  
end

Running this I get the following output:

rescuing raise from aux  
/Users/maasha/my\_aux\_class.rb:21:in `\<top (required)\>'  
./test.rb:3:in `require'  
./test.rb:3:in `\<main\>'  
exit status: OK  
Hello World  
Last exception was #\<RuntimeError: raise from main\>  
./test.rb:7:in `\<main\>': raise from main (RuntimeError)

I actually wanted the raise from main rescued, but the  
begin/rescue/ensure is misplaced/misused :o(

Martin

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Brian\_Candler](https://avatars.discourse-cdn.com/v4/letter/b/5f9b8f/32.png) [@Brian\_Candler](https://rubytalk.org/u/Brian_Candler)\
**Post date:** [6 August 2010 11:01 UTC](https://rubytalk.org/t/abstracting-exception-handling/59503/13 "2010-08-06T11:01:22Z")

</div>

Martin Hansen wrote:

> $! does not tell the difference between interrupt, terminate,  
> and quit (perhaps that could be fixed? - just a thought).

It does for me.

$ cat ert.rb  
at\_exit { puts "Last exception was #{$!.inspect}" if $!; exit! }  
sleep 100  
puts "Nothing happened"

### Ctrl-C:  
$ ruby ert.rb  
^CLast exception was Interrupt  
ert.rb:2:in `sleep': Interrupt  
&nbsp;&nbsp;from ert.rb:2

### kill -TERM (from another window):  
$ ruby ert.rb  
Last exception was #\<SignalException: SIGTERM\>  
Terminated

### kill -QUIT:  
Last exception was #\<SignalException: SIGQUIT\>  
Quit

This is with ruby 1.8.7 (2010-01-10 patchlevel 249) [x86\_64-linux] under  
Ubuntu Lucid amd64.

So I don't understand why you're trying to trap all of these signals,  
when they all cause the program to terminate, and they can all be  
distinguished in $!. But perhaps your platform behaves differently?

Final note: inside your at\_exit handler, you can use 'exit!' to prevent  
any further processing, i.e. the default output of the backtrace or  
signal.

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Brian\_Candler](https://avatars.discourse-cdn.com/v4/letter/b/5f9b8f/32.png) [@Brian\_Candler](https://rubytalk.org/u/Brian_Candler)\
**Post date:** [6 August 2010 11:04 UTC](https://rubytalk.org/t/abstracting-exception-handling/59503/14 "2010-08-06T11:04:18Z")

</div>

> at\_exit { puts "Last exception was #{$!.inspect}" if $!; exit! }

Actually, the sample output I showed was without the 'exit!'

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Martin\_Hansen](https://avatars.discourse-cdn.com/v4/letter/m/e36b37/32.png) [@Martin\_Hansen](https://rubytalk.org/u/Martin_Hansen)\
**Post date:** [6 August 2010 11:17 UTC](https://rubytalk.org/t/abstracting-exception-handling/59503/15 "2010-08-06T11:17:59Z")

</div>

This works great! I was sure I had tested this, but I had screwed up the  
test somehow - perhaps trap changed something. Anyways - this will work!

Thanks a zillion for the patient assistance!

Martin

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).
