Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby equivalent for Python's "try"?

I'm trying to convert some Python code into Ruby. Is there an equivalent in Ruby to the try statement in Python?

like image 504
thatonegirlo Avatar asked Sep 09 '13 19:09

thatonegirlo


People also ask

Does Ruby have try catch?

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).

Can I use Ruby and Python together?

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.


2 Answers

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.') 
like image 58
Óscar López Avatar answered Sep 23 '22 01:09

Óscar López


 begin      some_code  rescue       handle_error    ensure       this_code_is_always_executed  end 

Details: http://crodrigues.com/try-catch-finally-equivalent-in-ruby/

like image 23
zengr Avatar answered Sep 22 '22 01:09

zengr