Last active
December 16, 2022 19:50
-
-
Save aks/99bdc2c294d888308afc2091fd4a771c to your computer and use it in GitHub Desktop.
Show that rescue ordering determines exception handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
❯ ./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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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