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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.