在编程过程中为了增加友好性,在程序出现bug时一般不会将错误信息显示给用户让用户蒙逼,而是显示一个更友好的提示信息。
语法
try: """your code""" except Exception: """上面的程序执行出错后就指行这里的代码"""
需求:将用户输入的两个数字相加
while True: num1 = input('num1:') num2 = input('num2:') try: num1 = int(num1) num2 = int(num2) result = num1 + num2 except Exception as e: print('出现异常,信息如下:') print(e)
输入的不是数字的话,执行出错的异常就会把捕捉到
像上面这个Exception异常,几乎能捕捉到所有的错误,这不一定是好事,因为程序出错的原因有很多种,我可能希望出不同的错误就执行不同的异常处理逻辑。 全执行同一逻辑的话会增加程序调试难度,因为你不知道是什么原因导致的错误
常见异常类型
更多异常
IndexError例子
dic = ["wupeiqi", 'alex'] try: dic[10] except IndexError as e: print(e)
KeyError例子
info = {"name":"小猿圈","website":"http://apeland.cn"} try: info["addr"] except KeyError as e : print(e)
对于上述实例,异常类只能用来处理指定的异常情况,如果非指定异常则无法处理。
s1 = 'hello' try: int(s1) except IndexError as e: print(e)
所以,写程序时需要考虑到try代码块中可能出现的任意异常,可以这样写:
s1 = 'hello' try: int(s1) except IndexError as e: print(e) except KeyError as e: print(e) except ValueError as e: print(e)
如果上面3个异常依然没有匹配到对应的错误 怎么办? 可以在程序最后加上Exception这个万能异常。
s1 = 'hello' try: #int(s1) print(d) except IndexError as e: print(e) except KeyError as e: print(e) except ValueError as e: print(e) except Exception as e: print("最后的万能异常",e) 输出: 最后的万能异常 name 'd' is not defined
try: # 主代码块 pass except KeyError,e: # 异常时,执行该块 pass else: # 主代码块执行完,若未触发任何异常,执行该块 pass finally: # 无论监测的代码是否发生异常,都执行该处代码 pass
try: raise Exception('错误了。。。') except Exception as e: print(e)
以后你写的软件若想自定义一个异常的话,就可以用下面方法
class MyException(BaseException): # BaseException是所有异常的基类 def __init__(self,msg): self.message = msg def __str__(self): return self.message try: raise MyException("我的错误") except MyException as e: print(e)
assert语法用于判断代码是否符合执行预期
assert type(1) is int assert 1+1 == 2 assert 1+1 == 3 # 会报AssertionError
应用场景举例,别人调你的接口,你的接口要求他调用时必须传递指定的关键参数,等他传递进来时,你就可以用用assert语句他传的参数是否符合你的预期
def my_interface(name,age,score): assert type(name) is str assert type(age) is int assert type(score) is float my_interface("alex",22,89.2)