Ruby - Creating your own exception

Introduction

You can create new exception by subclassing existing exceptions.

Provide your classes with a to_str method in order to give them a default message.

class NoNameError < Exception
    def to_str
        "No Name given!"
    end
end

Here is an example of how you might raise a custom exception:

Demo

class NoNameError < Exception
    def to_str# w  w  w.  ja  v  a  2  s.  com
        "No Name given!"
    end
end

def sayHello( aName )
    begin
        if (aName == "") or (aName == nil) then
             raise NoNameError
        end
    rescue Exception => e
        puts( e.class )
        puts( "error message: " + e.to_s )
        puts( e.backtrace )
    else
        puts( "Hello #{aName}" )
    end
end

Related Topic