Try Except Else Finally in Python.

Let’s have a look at the below code:

try:
    k = m['name']
except:
    print('error occured')
else:
    print('all good')
finally:
    print('Done')

If an exception occurs in the code running between the try and except block, except block statements are executed. If nothing breaks in the try and except block, else block is executed. And at the end the finally block code gets executed.

The above code outputs:

error occured
Done

You can also print the exception error, when the except code block is executed.

try:
    k = m['name']
except Exception as e:
    print('error occured ' + str(e))
else:
    print('all good')
finally:
    print('Done')

Output

error occured name 'm' is not defined
Done