python - exception解析

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) 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值