Day 23 异常处理
异常处理
一、异常基本形式
# if # def test: # pass # class Foo # pass def test(): ''' 异常的基本类型和相关 :return: ''' try: # 检测代码 print("a") # except NameError as a: # print("Syn: ",a) except Exception as a: # 异常捕捉 print("Exc: ",a) else: # 无异常执行代码区 print("Its OK!") finally: # 无论如何,都执行代码区 print("over!")
二、异常自定义
class DachaoException(BaseException): def __init__(self,msg): self.msg = msg def __str__(self): return self.msg def test_1(): ''' 测试 自定义异常处理 类 :return: ''' try: raise DachaoException("我粗了") except DachaoException as a: print(a)
三、断言 assert
def test_2(): ''' 异常:断言assert,如果False,直接报错,且不执行下面信息 :return: ''' x = 10 y = 2 print("1") assert x < y print("2") print("3") print("4")
四、模拟异常处理
def test_3_1(): ''' if 模拟异常处理 :return: ''' while True: num1 = input(">>: ") if num1.isdigit(): int(num1) elif num1.isspace(): print("如果输入的是空格,就执行我这里的逻辑") elif len(num1) == 0: print("如果没有输入,就执行我这里的逻辑") else: print("啥也不说了,剩下的都跟我走了。") def test_3_2(): num2 = input(">>: ") int(num2) num3 = input(">>: ") int(num3) def test_3_3(): try: num2 = input(">>: ") int(num2) num3 = input(">>: ") int(num3) except ValueError as e: print(e)