How to make the "rescue" expression in a method

The code such as this:

begin
puts 1/0
Class::ex_handle
end
class Class
   def self.ex_handle
   rescue Exception
   puts $!
   end
end

The code above can not lead to an ideal result.It can not output the
exception normally.
However, the code if you change like this:
begin
puts 1/0
   rescue Exception
   puts $!
end
It works!
So it's my trouble.I want to make a method to handle exception very
carefully.So I want the "resuce" and other expressions in a method.But
if the "rescue" in a method,you know, it can not catch the exceptions
outside the method.
Please give me a solution if you know. Thank you very much!

···

--
Posted via http://www.ruby-forum.com/.

dongcan z. wrote in post #1056289:

So it's my trouble.I want to make a method to handle exception very
carefully.So I want the "resuce" and other expressions in a method.But
if the "rescue" in a method,you know, it can not catch the exceptions
outside the method.

You can rewrite the exception handling method to accept a block and
enclose the block in begin-rescue-end:

class Class
  def self.ex_handle
    begin
      yield
    rescue Exception
      puts $!
    end
  end
end

Class::ex_handle { puts 1/0 }

···

--
Posted via http://www.ruby-forum.com/\.

Hi,

You can define the method to accept a block and rescue exceptions coming
from the block:

def execute_and_rescue
  begin
    yield # execute the block
  rescue StandardError => error
    puts error.message
  end
end

execute_and_rescue do
  1/0
end

Some things to note:

- You current method definition doesn't really make sense, because you
neither do actual error handling nor do you suppress the error. What's
the purpose of the method? If you only want to change how error messages
are displayed, you should wrap the whole script in a begin-end block.

- It doesn't make sense to define the method as a singleton method of
class. If you want to use it everywhere, define it in the Kernel module.
Otherwise, define it in the specific class.

- Don't rescue instances of Exception, because this class also includes
system errors that you shouldn't touch. Rescue StandardError instead (or
even better: specific error classes).

- You can save the exact error object in the rescue block (see above).
Then you don't have to rely on the $! global variable.

···

--
Posted via http://www.ruby-forum.com/.