I'm trying to convert some Python code into Ruby. Is there an equivalent in Ruby to the try
statement in Python?
Asked
Active
Viewed 5.0k times
73

Óscar López
- 232,561
- 37
- 312
- 386

thatonegirlo
- 893
- 1
- 6
- 10
-
2show one code please! – Arup Rakshit Sep 09 '13 at 19:20
-
Look up Ruby `rescue` (and `raise`) – lurker Sep 09 '13 at 19:21
3 Answers
134
Use this as an example:
begin # "try" block
puts 'I am before the raise.'
raise 'An error has occurred.' # optionally: `raise Exception, "message"`
puts 'I am after the raise.' # won't be executed
rescue # optionally: `rescue StandardError => ex`
puts 'I am rescued.'
ensure # will always get executed
puts 'Always gets executed.'
end
The equivalent code in Python would be:
try: # try block
print('I am before the raise.')
raise Exception('An error has occurred.') # throw an exception
print('I am after the raise.') # won't be executed
except: # optionally: `except Exception as ex:`
print('I am rescued.')
finally: # will always get executed
print('Always gets executed.')

Óscar López
- 232,561
- 37
- 312
- 386
-
2There's also the quirky `else` clause that gets executed only if no exceptions have been triggered. – tadman Sep 09 '13 at 19:32
-
-
1one of the best answers on SO from both a form and content perspective; much thanks – d8aninja Dec 01 '20 at 13:17
-
1It's better to rescue `StandardError` instead of `Exception` (as in the comment in the Ruby example): https://stackoverflow.com/q/10048173/12484 – Jon Schneider Aug 30 '22 at 22:02
13
begin
some_code
rescue
handle_error
ensure
this_code_is_always_executed
end
Details: http://crodrigues.com/try-catch-finally-equivalent-in-ruby/

zengr
- 38,346
- 37
- 130
- 192
3
If you want to catch a particular type of exception, use:
begin
# Code
rescue ErrorClass
# Handle Error
ensure
# Optional block for code that is always executed
end
This approach is preferable to a bare "rescue" block as "rescue" with no arguments will catch a StandardError or any child class thereof, including NameError and TypeError.
Here is an example:
begin
raise "Error"
rescue RuntimeError
puts "Runtime error encountered and rescued."
end

Zags
- 37,389
- 14
- 105
- 140