Ruby equivalent for Python's “try”?

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

Can anyone help me with this?
Jul 29 in Python by ana1504.k
• 7,870 points
9 views

1 answer to this question.

0 votes

Use this as an example:

begin  # "try" block
    puts 'I am before the raise.'  
    raise 'An error has occured.' # 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 occured.') # 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.'
answered Jul 29 by SDeb
• 13,160 points

Related Questions In Python

0 votes
1 answer

What is the Python equivalent for a case/switch statement?

if x == 'a':  # Do the ...READ MORE

answered Jul 26, 2018 in Python by Priyaj
• 56,200 points
80 views
0 votes
1 answer

Python equivalent for static variables within a function?

You can use the following code, that ...READ MORE

answered Oct 17, 2018 in Python by Priyaj
• 56,200 points
313 views
0 votes
1 answer

What is equivalent for 'foreach' in Python

Its also interesting to observe this To iterate ...READ MORE

answered Oct 17, 2018 in Python by findingbugs
• 4,750 points
31 views
0 votes
1 answer

wcopyfind equivalent for python

Hi @Ashish, you can use the difflib ...READ MORE

answered Aug 5 in Python by Tara
9 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 169 views
0 votes
1 answer

Equivalent for easy_install & pip

For pip you can check the User ...READ MORE

answered Nov 28, 2018 in Python by SDeb
• 13,160 points
57 views
0 votes
1 answer

Return a list inside a for loop while iterating over the elements of another list

The print() is getting called multiple times ...READ MORE

answered Sep 21, 2018 in Python by SDeb
• 13,160 points
50 views