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",)
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
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
1#Best practive: raise statement
2raise ValueError('A very specific bad thing happened')