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.
Since the try block raises an error, the except block will be executed.
Yes, You read it right! It can be done. We can use Try ( Exception Handling ) instead of using normal conditional statements.
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.
You want else
:
for i in [0, 1]: try: print '10 / %i: ' % i, 10 / i except: print 'Uh-Oh' else: print 'Yay!'
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
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