Ruby - Raise an exception

Introduction

You can raise your exceptions to force an error condition even when the program code has not caused an exception.

Calling raise on its own raises an exception of the type RuntimeError or whatever exception is in the global variable $!:

raise # raises RuntimeError

By default, this will have no descriptive message associated with it. You can add a message as a parameter, like this:

raise "An unknown exception just occurred!"

You can raise a specific type of error:

raise ZeroDivisionError

You can create an object of a specific exception type and initialize it with a custom message:

raise ZeroDivisionError.new( "I'm afraid you divided by Zero" )

This is a simple example:

Demo

begin
    raise ZeroDivisionError.new( "divided by Zero" )
rescue Exception => e#   w  w  w  .j  a  va 2  s  . co m
    puts( e.class )
    puts( "message: " + e.to_s )
end

Result

Related Topic