异常

不想让用户看到直接的错误提示:

1. 一个小例子

data={}
try:
    data["name"]
except KeyError as e:
    print("没有这个key",e)

 运行结果:

没有这个key 'name'

 

2.多个错误同时判断,Error1,Error2 是或者的关系,只要有一个出错,就打印e

try:
    code
except(Error1,Error2) as e:
    print e

 

3. 所有错误一把抓,但是不知道具体是哪个出错了。(一般不用,否则无法调错。一般用在末尾,用于抓所有未知错误)

name=["alex","Jack"]
data={}
try:
    name[3]
    data["name"]
except(KeyError,IndexError) as e:
print("没有这个key",e) except Exception as e: #抓住所有的错误,但是不利于后期的调试。建议放到找错误的最后部分,当找不到其他错误的时候,用这个找未知错误。 print("未知错误",e)
else:
print("一切正常")
Finally:
print("不管有没有错,都执行")

 运行结果:

出错了 list index out of range

 4.自定义的异常:

class AlexException(Exception):
    def __init__(self,msg):
        self.message=msg
    def __str__(self):
        return "abcde"

try:
    raise AlexException('数据库连不上') #触发异常
except AlexException as e:
    print(e)

 运行结果:

abcde

 5.补充:断言(assert)

assert type(obj.name) is int #如果断言正确,则往下执行;如果断言错误,则报错。相当于一个检查工作。

print(obj.name/2)

 

posted on 2017-08-01 12:04  momo8238  阅读(130)  评论(0编辑  收藏  举报