From: timsuth@... (Tim Sutherland) Date: 2004-11-03T19:43:50+09:00 Subject: Re: Programmatically and dynamically catching exceptions In article <2urqndF2cbspnU1@uni-berlin.de>, Robert Klemme wrote: > >"Logan Capaldo" schrieb im Newsbeitrag >news:4521f6680411022134451a94d1@mail.gmail.com... >> Thanks thats quite neat. >> >> On Wed, 3 Nov 2004 13:20:28 +0900, Yohanes Santoso >> wrote: >> > Logan Capaldo writes: >> > >> > >> > >> > > Allright here was my idea which seems to have been shattered by the >> > > realities of Ruby. >> > > >> > > I was thinking of a class called Try. You would do something like >> > > >> > > class Try >> > > ... >> > > end >> > > >> > > tryblock = Try.new { #This block would normally be wrapped in a >begin...rescue >> > > } >> > > >> > > tryblock.add_exhandler(:SomeException) { |ex| some_code } >> > > >> > > tryblock.execute #or possibly tryblock.call ? >> > > >> > > Basically the idea was going to be you could subclass Try and >provide >> > > default sensible handling of your Exceptions (if you were writing a >> > > library for instance) . Users could then then wrap it in a >> > > begin...rescue block to catch other exceptions or use add_exhandler >to >> > > overide the default handler. (Possibly provide a way to get the old >> > > handler and and use it in the new). >> > > >> > > my idea was going to be that I could do something like >> > > >> > >> > class Try >> > def execute >> > begin >> > user_proc.call(*user_proc_args) >> > rescue Error => e >> > elt = (exhandlers.select{|obj| e.class == >obj.exception_class})[0] >> > if elt >> > elt.exception_handler.call(e) >> > else >> > raise e >> > end >> > end >> > end >> > end > >We can save three more lines :-) > >class Try > def execute > begin > user_proc.call(*user_proc_args) > rescue Error => e > elt = (exhandlers.select{|obj| e.class == obj.exception_class})[0] > raise unless elt > elt.exception_handler.call(e) > end > end >end As long as we're saving lines... class Try def execute user_proc.call(*user_proc_args) rescue Error => e elt = (exhandlers.select{|obj| e.class == obj.exception_class})[0] or raise elt.exception_handler.call(e) end end