raise: Reactivate a Handled Error

Sometimes you may want to keep an exception “alive” even after it has been trapped in an exception-handling block. You can do this, for example, to defer the handling of the exception, say by passing it on to some other method. You can do this using the raise method. You need to be aware, however, that, once raised, an exception needs to be rehandled; otherwise, it may cause your program to crash. Here is a simple example of raising a ZeroDivisionError exception and passing on the exception to a method called, in this case, handleError:

raise.rb

begin
    divbyzero
rescue Exception => e
    puts( "A problem just occurred. Please wait..." )
    x = 0
    begin
        raise
    rescue
        handleError( e )
    end
end

Here divbyzero is the name of a ...

Get The Book of Ruby now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.