1try:
2 print("I will try to print this line of code")
3except:
4 print("I will print this line of code if an error is encountered")
1try:
2 print("I will try to print this line of code")
3except ERROR_NAME:
4 print("I will print this line of code if error ERROR_NAME is encountered")
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')
1>>> def divide(x, y):
2... try:
3... result = x / y
4... except ZeroDivisionError:
5... print("division by zero!")
6... else:
7... print("result is", result)
8... finally:
9... print("executing finally clause")
10...
11>>> divide(2, 1)
12result is 2.0
13executing finally clause
14>>> divide(2, 0)
15division by zero!
16executing finally clause
17>>> divide("2", "1")
18executing finally clause
19Traceback (most recent call last):
20 File "<stdin>", line 1, in <module>
21 File "<stdin>", line 3, in divide
22TypeError: unsupported operand type(s) for /: 'str' and 'str'
23
1try:
2 x > 3
3except:
4 print("Something went wrong")
5else:
6 print("Nothing went wrong")
7finally:
8 print("The try...except block is finished")