Skip to content

Instantly share code, notes, and snippets.

@aks
Last active December 16, 2022 19:50
Show Gist options
  • Save aks/99bdc2c294d888308afc2091fd4a771c to your computer and use it in GitHub Desktop.
Save aks/99bdc2c294d888308afc2091fd4a771c to your computer and use it in GitHub Desktop.
Show that rescue ordering determines exception handling
❯ ./ruby-rescue-ordering-test.rb
Next? [eis] e
StandardError handler # Encoding is a subclass of StandardError
this is an encoding error
Next? [eis] i
StandardError handler # IOError is also a subclass of StandardError
this is an IO error
Next? [eis] s
ScriptError handler # ScriptError is NOT a subclass of StandardError
this is a script error
Next? [eis] %
# conclusion: rescues are attempted in the order given. First one that matches, wins.
#!/usr/bin/env ruby
# Test class
class Test
def failer(what = nil)
case what
when 'e', 'enc', 'encoding'
raise EncodingError, 'this is an encoding error'
when 's', 'script', 'scr'
raise ScriptError, 'this is a script error'
when 'i', 'ioerr', 'ioerror'
raise IOError, 'this is an IO error'
else
raise 'ArgumentError', 'no argument'
end
rescue StandardError => e
puts 'StandardError handler'
puts e.message
rescue ScriptError => e
puts 'ScriptError handler'
puts e.message
rescue EncodingError => e
puts 'EncodingError handler'
puts e.message
rescue IOError => e
puts 'IOError handler'
puts e.message
end
def prompt(msg)
print msg
gets
end
def run
while (ans = prompt('Next? [eis] '))
failer(ans.strip)
end
end
end
Test.new.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment