1try:
2 raise Exception("Oh no! An error happened!")
3except Exception as err:
4 print("An error was handled")
5finally:
6 print("This runs either way.")
1import traceback
2
3dict = {'a':3,'b':5,'c':8}
4try:
5 print(dict[q])
6
7except:
8 traceback.print_exc()
9
10# This will trace you back to the line where everything went wrong.
11# So in this case you will get back line 5
12
13
1try:
2 # Code to test / execute
3 print('Test')
4except (SyntaxError, IndexError) as E: # specific exceptions
5 # Code in case of SyntaxError for example
6 print('Synthax or index error !')
7except :
8 # Code for any other exception
9 print('Other error !')
10else:
11 # Code if no exception caught
12 print('No error')
13finally:
14 # Code executed after try block (success) or any exception (ie everytime)
15 print('Done')
16
17# This code is out of try / catch bloc
18print('Anything else')