module Try

A module that attempts to provide some of the expressive power offered by MOO Code through the following language constructs:

`unsafe_expression ! ANY'
`unsafe_expression ! ANY => fallback_expression'
`unsafe_expression ! E_FOO, E_BAR'
`unsafe_expression ! E_FOO, E_BAR => fallback_expression'

In Ruby these become:

Try.try { unsafe_expression }  # OR: unsafe_expression rescue $!
Try.trap(Exception=>fallback) { unsafe_expression }  # OR: unsafe_expression rescue fallback
Try.trap(FooError, BarError) { unsafe_expression}
Try.trap(FooError=>fallback, BarError=>fallback) { unsafe_expression }

Constants

ORIG

In trap this can be used to map an class of exception to the raised exception itself.

Public Instance Methods

test(*errs) { || ... } click to toggle source

Evaluates the given block and returns its value. If an exception is raised, nil is returned instead.

If ((%errs%)) are given, only those exceptions will be trapped, and any other exceptions will be raised normally.

@param errs an optional list of exception types to trap.

   # File lib/try.rb
73 def test *errs, &bk
74   yield
75 rescue Exception => ex
76   return nil if errs.empty?
77   errs.each do |klass|
78     return nil if klass.instance_of?(Module) ? ex.kind_of?(klass) : ex.is_a?(klass)
79   end
80   raise
81 end
trap(*errs) { || ... } click to toggle source

Evaluates the given block and returns its value.

Specific exception types can be trapped by passing them as parameters.

Additionally, specific exception types can default to a fallback value if passed as (({Type => value})) pairs. If the value is a Proc, it is called and the exception object is passed as a parameter. If the value is Try::ERROR, the exception object itself is returned.

Any un-trapped exception is raised normally.

@param errs a list of exception types to trap.

   # File lib/try.rb
49 def trap *errs, &bk
50   hash = {}
51   hash = errs.pop if errs.last.is_a? Hash
52   errs.each {|ec| hash[ec] = ec }
53   yield
54 rescue Exception => ex
55   errs.each do |klass|
56     return ex if klass.instance_of?(Module) ? ex.kind_of?(klass) : ex.is_a?(klass)
57   end
58   hash.each_pair do |klass,value|
59     return value.is_a?(Proc) ? value.call(ex) : (value.equal?(ORIG) ? ex : value) if klass.instance_of?(Module) ? ex.kind_of?(klass) : ex.is_a?(klass)
60   end
61   raise
62 end
try() { || ... } click to toggle source

Evaluates the given block and returns its value. If an exception is raised, that exception is returned instead.

   # File lib/try.rb
27 def try &bk
28   yield
29 rescue Exception => ex
30   ex
31 end