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, 2019 in Python by ana1504.k
• 7,910 points
753 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, 2019 by SDeb
• 13,300 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
• 58,090 points
750 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
• 58,090 points
4,454 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,780 points
2,172 views
0 votes
1 answer

wcopyfind equivalent for python

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

answered Aug 6, 2019 in Python by Tara
473 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,055 views
0 votes
1 answer
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,300 points
887 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 22, 2018 in Python by SDeb
• 13,300 points
4,672 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP