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 # from  ww  w . j a v  a 2  s . co  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