I'm trying to convert some Python code into Ruby. Is there an equivalent in Ruby to the try
statement in Python?
In Ruby we have a way to deal with these cases, we have begin, end(default try catch) and we can use try and catch, both try catch and raise rescue used for the same purpose, one will throw exception(throw or raise) with any specific name inside another(catch or rescue).
Using Ruby with Python - a powerful combination If you want to build a web app that looks great, delights users, and handles Big Data or uses Machine Learning, joining the forces of Python and Ruby is a very good idea.
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 Exception => 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.')
begin some_code rescue handle_error ensure this_code_is_always_executed end
Details: http://crodrigues.com/try-catch-finally-equivalent-in-ruby/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With