1. example of exception
try:
print('try...')
r = 10 / int('2')
print('result:', r)
except ValueError as e:
print('ValueError:', e)
except ZeroDivisionError as e:
print('ZeroDivisionError:', e)
else:
print('no error!')
finally:
print('finally...')
print('END')
try...
result: 5.0
no error!
finally...
END
2.exception 的层级结构
# 第二个except永远也捕获不到UnicodeError,因为UnicodeError是ValueError的子类,如果有,也被第一个except给捕获了。
def foo(s):
print (10/int(s))
try:
foo(5)
except ValueError as e:
print('ValueError')
except UnicodeError as e:
print('UnicodeError')
3. 自定义exception
# 自定义 exception (尽量使用Python内置的错误类型)
import math
class number_TypeError(ValueError):
pass
def hanshu(x,y,a,angle):
try:
if not isinstance(x,(int,float)):
raise number_TypeError("wrong type!")
nx=x+a*math.cos(angle)
ny=y+a*math.sin(angle)
print(nx,ny)
except number_TypeError as err:
print("Exception:",err)
hanshu('100',80,10,math.pi/2)
Exception: wrong type!
e.g.2
from https://www.cnblogs.com/Lival/p/6203111.html
class MyException(Exception):
def __init__(self,message):
Exception.__init__(self)
self.message=message
a=input("please input a num:")
if a<10:
try:
raise MyException("my excepition is raised ")
except MyException as e:
print (e.message)
4. raise exception to upper function
# 当前函数不知道应该怎么处理该错误,所以,最恰当的方式是继续往上抛,让顶层调用者去处理
def foo(s):
n = int(s)
if n==0:
raise ValueError('invalid value: %s' % s)
return 10 / n
def bar():
try:
foo('0')
except ValueError as e:
print('ValueError!')
raise # 发现异常,并上报
try:
bar()
except Exception as err:
print("Exception:",err)
ValueError!
Exception: invalid value: 0
5. skip任意异常
If there is no path between two nodes in a directed graph, it will raise error when calling nx.shortest_path().
def Closeness_Centrality(nodes_num, source_id):
total_count = 0
for target_id in range(1, nodes_num+1):
if target_id == source_id:
continue
else:
try:
this_shortest_path = nx.shortest_path(IEMS_social_network, source=source_id, target=target_id)
total_count += (len(this_shortest_path) - 1)
except Exception as e:
# No path between these two nodes
print("Exception:",e)
continue
closeness_centrality = (1 / total_count) * (nodes_num-1)
return closeness_centrality
nodes_num = IEMS_social_network.number_of_nodes()
result = Closeness_Centrality(nodes_num, MY_ID)
print('Closeness_Centrality: ', result)