python 异常处理

1、异常处理使用Exception类,也可自定义异常

2、异常处理流程:

try:

  pass

except Exception,e

  pass

else:

  pass

finally:

  pass

3、手动触发异常raise

 

try:
data = raw_input('请输入URL:')
arr = data.split('/')
namespace = __import__('backend.' + arr[0])
model = getattr(namespace, arr[0])
func = getattr(model, arr[1])
func()

except Exception, e:
print '捕捉异常', e
else:
print '没有异常'
finally:
print '无论异常与是都将执行'

# 自定义异常
class myException(Exception):
def __init__(self, msg):
self.error = msg

def __str__(self, *args, **kwargs):
return self.error

obj = myException('错误')
print obj
# __str__被print函数调用
# raise myException('打印错误') # 手动触发异常

 

posted @ 2016-06-12 17:08  3one  阅读(91)  评论(0编辑  收藏  举报