Exception Errors in Ruby - jbkimble/Jons_wiki GitHub Wiki

Definitions

Exception: Ruby's way of dealing with unexpected events (i.e. SyntaxError, NoMethodError, ZeroDivisionError)

Rescuing, Handling, Catching: All terms for handling an error intelligently rather than having the program crash

Exception objects: normal Ruby object that holds the data about "what happened" for the exception you just rescued

Examples

def exception_example
begin
      1/0
rescue
      puts "Area where code is executed if there is an exception"
      # Put some code here that intelligently responds
end
def exception_object_example
  1/0
  pandabear
  # rescues all errors and puts them in the exception object 'e'
rescue => e
  puts e.message
end
def specfic_exception_class_example_with_debug_data
  # 1/0
  pandabear
  # Rescues only ZeroDivisionError and puts the exception object in `e`
rescue ZeroDivisionError => e
  puts e.message
  # additional debug data contained in exception object
  puts "Exception Class: " + e.class.name
  puts "Exception Backtrace: " + e.backtrace
end
def rescue_multiple_errors
  1/0 # or some other error
rescue ZeroDivisionError, NameError => e
  puts e.message
end
def raise_my_own_exception
  #raises an ArgumentError with the message "Fatal error"
  raise ArgumentError.new("Fatal error")
  # additional syntax to raise an exception
  # raise RuntimeError.new("Fatal error")
  # raise RuntimeError, "Fatal error"
  # raise "Fatal error!"
rescue ArgumentError => e
  puts e.message
end
def catch_all_relevant_excetions
  # or other error besides divide by 0
  1/0
  # DONT RESCUE ALL ERRORS, if you want to catch all errors that
  # are relevant from a users perspective us the StandardError class
  rescue StandardError => e
  print "Great job rescuing: " + e.message
end

Quiz

  • What is an argument error?
  • Why do argument errors exist?
  • When should I use one?
  • What is the standard error class I should use in my rescue object assignment? (the one that will capture all relevant areas for my uses)