python——简单的异常处理

#异常处理格式
"""""
try:
    #代码块
     z=int(input())
     print(z)
except Exception as e:
    #上述代码出错,自动执行当前块的内容
    print(1)
    """

"""""
Exception是全部的错误
常见错误有:
IndexError
ValueError等
"""
try:
    int('war')
except IndentationError as e:#对应到其中一个就不再执行
    print('IndexError',e)
except ValueError as e:
    print('ValueError',e)
except Exception as  e:
    print('Exception',e)
else:#没错执行else里 有错执行对应的except
    print('meicuo')
finally:#最后必须执行
    print('finally')

"""""
#主动触发错误:用于记录日志
def db():
    return False
def index():
    try:
        r=input(">>")
        int(r)
        result=db()
        if not result:
            raise Exception('数据库处理错误')
    except Exception as e:
        str_error=str(e)
        print(str_error)
        r=open(str_error)
        r=open('log','a')
        r.write(str_error)
index()
"""
#自定义一个错误
class OldBoyError(Exception):
    def __init__(self,msg):
        self.message=msg
    def __str__(self):
        return self.message
try:
    raise OldBoyError('错误')
except OldBoyError as e:
    print(e)#e对象的__str__()方法,获取返回


#assert条件,断言,用于强制用户服从,不服从就报错
print(123)
assert 2==2
print(456)

 

posted @ 2019-09-01 21:59  zzzi  阅读(251)  评论(0编辑  收藏  举报