Python 异常处理
一、异常基础
1、在编程过程中为了增加友好性,在程序出现bug时一般不会将错误信息显示给用户,而是显示一个提示的页面,通俗来说就是不让用户看见大黄页。
try: num1 = input("num1:") num2 = input("num2:") num1 = int(num1) num2 = int(num2) reslut = num1 + num2 #先尽量捕获已知的异常最后再捕获万能异常 except ValueError as e: print("value err",e) except IndexError as e: print("index err:",e) except Exception as e: print("异常情况如下:",e)
二、自定义异常
class PresleyException(Exception): def __init__(self,msg): self.message = msg def __str__(self): return self.message try: raise PresleyException("我的异常") except PresleyException as e: print(e)
三、断言
class PresleyException(Exception): def __init__(self,msg): self.message = msg def __str__(self): return self.message a = 1 try: #assert 断言 #assert a == 1 #如果a == 1那么就过了,因为a=1所以过 assert a == 2 #因为a =1所以不过,然后走到异常 #raise PresleyException("我的异常") except PresleyException as e: print(e)
四、finally
class PresleyException(Exception): def __init__(self,msg): self.message = msg def __str__(self): return self.message a = 1 try: #assert 断言 #assert a == 1 #如果a == 1那么就过了,因为a=1所以过 assert a == 2 #因为a =1所以不过,然后走到异常 #raise PresleyException("我的异常") except PresleyException as e: print(e) finally: #无论前面怎么样都执行此下面的步骤 print("no matter right or wrong,run this anyway")
五、else
#!/usr/bin/python # -*- coding : utf-8 -*- # 作者: Presley # 时间: 2018-11-12 # 邮箱:1209989516@qq.com # 这是我用来练习异常的测试脚本 class PresleyException(Exception): def __init__(self,msg): self.message = msg def __str__(self): return self.message a = 1 try: #assert 断言 assert a == 1 #如果a == 1那么就过了,因为a=1所以过 #assert a == 2 #因为a =1所以不过,然后走到异常 #raise PresleyException("我的异常") except PresleyException as e: print(e) else: print("没有异常") finally: #无论前面怎么样都执行此下面的步骤 print("no matter right or wrong,run this anyway")