1>>> def catch():
2... try:
3... asd()
4... except Exception as e:
5... print e.message, e.args
6...
7>>> catch()
8global name 'asd' is not defined ("global name 'asd' is not defined",)
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")
1>>> try:
2... raise Exception('spam', 'eggs')
3... except Exception as inst:
4... print(type(inst)) # the exception instance
5... print(inst.args) # arguments stored in .args
6... print(inst) # __str__ allows args to be printed directly,
7... # but may be overridden in exception subclasses
8... x, y = inst.args # unpack args
9... print('x =', x)
10... print('y =', y)
11...
12<class 'Exception'>
13('spam', 'eggs')
14('spam', 'eggs')
15x = spam
16y = eggs
17
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