Ruby - Exception raising exceptions

Introduction

An exception is an event that occurs when an error arises within a program.

Ruby exceptions are packaged into objects of class Exception or one of Exception's many subclasses.

Ruby has about 30 main predefined exception classes, such as NoMemoryError, RuntimeError, SecurityError, ZeroDivisionError, and NoMethodError.

One of the standard exception classes is ArgumentError, which is used when the arguments provided to a method are fatally flawed.

You can use this class as an exception if bad data is supplied to a method of your own:

Demo

class Person 
  def initialize(name) 
    raise ArgumentError, "No name present" if name.empty? 
  end # w  w  w .j  a va  2s. c o m
end 

fred = Person.new('')

Result

You can call raise with no arguments at all, and a generic RuntimeError exception will be raised.

Related Topics