DEV Community

loading...

Ruby Exception handling

K-Sato
SWE based somewhere on earth.
・2 min read

Table of contents

Basic Syntax

The basic syntax of ruby's exception handling looks like this.

begin 
  # Code that potentially raises an error  
rescue => e # variable
  # Execute if there was an error between begin and rescue.
end
Enter fullscreen mode Exit fullscreen mode

Example

begin 
  raise 
rescue => e
  p e #=> RuntimeError
end
Enter fullscreen mode Exit fullscreen mode

Relevant methods

Method Explanation
Object#class Returns the class of the receiver.
Kernel#raise Raise an error.
Exception#backtrace Returns the backtrace of the error.
Exception#message Returns the error message.

Example

begin 
  raise StandardError.new("Message")
rescue => e
  p e.class #=> StandardError
  p e.message #=> "Message"
  p e.backtrace #=> ["(repl):4:in `<main>'", "/run_dir/repl.rb:41:in `eval'", "/run_dir/repl.rb:41:in `run'", "/run_dir/repl.rb:57:in `handle_eval'", "/run_dir/repl.rb:170:in `start'", "/run_dir/repl.rb:177:in `start'", "/run_dir/repl.rb:181:in `<main>'"]
end
Enter fullscreen mode Exit fullscreen mode

Ensure

You can run something regardless of the existence of an error with ensure

Example

begin 
  "no Error"
rescue => e
  p e.message
ensure 
  p "Ensured" #=> Ensured
end
Enter fullscreen mode Exit fullscreen mode

Example2

begin 
  raise StandardError.new('error')
rescue => e
  p e.message #=> error
ensure 
  p "Ensured" #=> Ensured
end
Enter fullscreen mode Exit fullscreen mode

Retry

Literally re-try the execution.

Example

file = ARGV[0]

begin
  # Open a file.
  io = File.open( file )
rescue
  # If there was an error during opening the file, this part gets executed.

  sleep( 10 )
  # Goes back to begin and re-try the execution.
  retry
end
Enter fullscreen mode Exit fullscreen mode

Rescue modifier

You can write begin ~ rescue in one sentence just like if ~ end in Ruby.

Example

raise "Error" rescue p "rescued" #=> rescued
Enter fullscreen mode Exit fullscreen mode

Exception in methods

You don't need to write begin and end to do exception handling in methods.

Example

def method
 raise 'error'
 rescue => e 
  p e.message #=> error
 ensure
  p 'ensured' #=> ensured
end
method #=> "error"
Enter fullscreen mode Exit fullscreen mode

Multiple Exceptions

You can write rescue multiple times for each corresponding error.

begin 
  rescue Exception1, Exception2 => e
  # For Exception1 or Exception2
  rescue Exception3 => e
  # For Exception3
  rescue => e
   # For other errors.
end
Enter fullscreen mode Exit fullscreen mode

Example

begin 
  raise StandardError
  rescue StandardError, RangeError   
    p 'Standard or Ranage Error'
  rescue RuntimeError
    p 'Runtime Error'
  rescue => e
    p 'some other error'
end

#=> "Standard or Ranage Error"
Enter fullscreen mode Exit fullscreen mode

Custom Exception

Simply Follow the steps below.

(1) Make a new Class

class CustomError < StandardError
end
Enter fullscreen mode Exit fullscreen mode

(2) Add a message

class CustomError < StandardError
  def initialize(msg="My Error")
    super
  end
end
Enter fullscreen mode Exit fullscreen mode

(3) Add custom data attributes to your exception

class CustomError < StandardError
  attr_reader :atr
  def initialize(msg="My Error", atr="atrribute")
    @atr = atr
    super(msg)
  end
end
Enter fullscreen mode Exit fullscreen mode

Example

class CustomError < StandardError
  attr_reader :atr

  def initialize(msg="My Error", atr="atrribute")
    @atr = atr
    super(msg)
  end
end


begin
  raise CustomError.new("CustomMessage", "Custom Attribute")
rescue => e
  p e.message #=> "CustomMessage"
  p e.atr  #=> "Custom Attribute"
end
Enter fullscreen mode Exit fullscreen mode

References

Discussion (2)

Collapse
coderzpro profile image
Coderzpro • Edited

In ruby, exception managing is a technique which describes a way to deal with the error raised in a software. Here ENGLISH LANGUAGE PROGRAM , error manner an unwanted or unexpected event, which takes place at some stage in the execution of a program, i.E. At run time, that disrupts the regular waft of this system’s instructions. So those sorts of errors have been handled via the rescue block.

Collapse
meave9786 profile image
meave9786

It is the best blog to all over read it thanks for share how do you get robux for free this information and start be great fun any time.