Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

running code if try statements were successful in python

I was wondering if in python there was a simple way to run code if a try statement was successful that wasn't in the try statement itself. Is that what the else or finally commands do (I didn't understand their documentation)? I know I could use code like this:

successful = False try:     #code that might fail     successful = True except:     #error handling if code failed if successful:     #code to run if try was successful that isn't part of try 

but I was wondering if there was a shorter way.

like image 230
None Avatar asked May 08 '10 01:05

None


People also ask

Will be executed if the try block raises an error?

Since the try block raises an error, the except block will be executed.

Can we use if in TRY in Python?

Yes, You read it right! It can be done. We can use Try ( Exception Handling ) instead of using normal conditional statements.

Does code continue after try except?

If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then, if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try/except block.


2 Answers

You want else:

for i in [0, 1]:     try:         print '10 / %i: ' % i, 10 / i     except:         print 'Uh-Oh'     else:         print 'Yay!' 
like image 108
Jesse Aldridge Avatar answered Oct 13 '22 00:10

Jesse Aldridge


You are looking for the else keyword:

try:     #code that might fail except SomeException:     #error handling if code failed else:     # do this if no exception occured 
like image 35
unutbu Avatar answered Oct 13 '22 01:10

unutbu