Python基础语法(十一)异常

2018-01-26  本文已影响0人  狂浪的心

异常

#coding=utf-8

try:
    num = input("xxx:")
    int(num)
    #11/0
    #open("xxx.txt")
    #print(num)
    print("-----1----")

except (NameError,FileNotFoundError):
    print("如果捕获到异常后做的 处理....")
except Exception as ret:
    print("如果用了Exception,那么意味着只要上面的except没有捕获到异常,这个except一定会捕获到")
    print(ret)
else:
    print("没有异常才会执行的功能")
finally:
    print("------finally-----")

print("-----2----")

如果是NameError,FileNotFoundError类型的异常会进入此异常,否则其他的都进入Exception 异常,except 进入后就不会进入else,没有异常会进入else,有没有异常都会进入finally中

自定义异常


class ShortInputException(Exception):
    def __init__(self,length,atleast):
        self.length = length
        self.atleast = atleast

def test():
    try:
        if True:
            raise ShortInputException(2,3)
    except ShortInputException as result:
        print (u"输入的长度是%d,最少长度是%d"%(result.length,result.atleast))
    else:
        print (u"没有异常发生")

test()

通过raise来向上抛出异常

上一篇 下一篇

猜你喜欢

热点阅读