Python必须知道的异常处理

异常处理

把可能会发生的错误,提前在代码里进行捕捉(监测)

try :

  code

except Exception:

出错后要执行的代码  

下面是常见的异常: 

attributeError  试图访问一个对象没有的属性

Nameerror 访问一个没有变量

Valueerror 值类型不匹配

importError  导入不存在的模块

indentationError 缩进错误 -->  强类型错误,只要犯这种错误程序就会崩溃,这种错误是抓不到的

syntaxError  语法错误  --> 同上

indexError  下标索引超出边界错误 

Keyboardinterrupt   ctrl+c 无法退出程序 

EOFError    ctrl+d  无法退出程序

Typeerror  类型不符合

Unboundlocalerror  试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,导致你以为正在访问它

valueError  传入一个调用者不期望的值,及时值的类型是正确的

# -*- coding:utf-8 -*-

while True:
    num1 = input("num1>>").strip()
    num2 = input("num2>>").strip()
    try:
        num1 = int(num1)
        num2 = int(num2)
        result = num1 + num2
        print(result,name)
    # except Exception as err:
    #     print("info is error. check")
    #     print(err)
    except NameError as e:
        print(e)
    except ValueError as e:
        print(e)

Try ..else..finally  

Else 不触发异常执行里边的代码

Finally 无论触发异常与否都会执行里边的代码

  

自定义异常

# -*- coding:utf-8 -*-
#自定义异常

class YoutubeConnectionError(BaseException):
    def __init__(self,msg):
        self.msg = msg

    def __str__(self):
        return self.msg


name = "Alex"
d = [1,2,3]

while True:
    num1 = input("num1>>").strip()
    num2 = input("num2>>").strip()
    try:
        num1 = int(num1)
        num2 = int(num2)
        result = num1 + num2
        print(result)
        #raise ImportError('123')
        raise YoutubeConnectionError('根据法律不能翻墙')#主动触发异常
        #d[3]
    # except Exception as err:
    #     print("info is error. check")
    #     print(err)笔
    except YoutubeConnectionError as e:
        print(e)
    except NameError as e:
        print(e)
    except ValueError as e:
        print(e)
    except Exception as e:
        print('发生错误')
    else:
        print("Normal!!!,不发生异常走这里")
    finally:
        print('any无论错误与否,都会走这里')

Assert 断言的用途

Assert语法用于判断代码是否符合执行预期

Assert 1+1=2

Assert 1+ 2 = 2

它一般用来做单元测试,调用上千个借口,看是都会出现异常

def my_interface(name,age,sorce):
    assert type(name) is str
    assert type(age) is int
    assert type(sorce) is float

my_interface("Alex",22,66.3)
原文地址:https://www.cnblogs.com/zjaiccn/p/13220517.html