python异常处理
-
异常
try: #try必须有语句执行要不然 下面的 except 报错 11/0 # print(num) #系统检测到错误 不会执行 try 里剩下的代码 直接去 except 下面去找同等的错误类型 # open("xxx.txt") print("----1----") #except NameError: # print("没有这个变量名....") #如果所有except上的错误类型都没有try上的那个错误类型 那就报错 因为系统没 #检测到你判断的这种类型 #所以直接按系统的那种报错方案 报错 直接把你干死 #except FileNotFoundError: # print("文件不存在....") #可以把类型错误写在一起 用元组的方式 except (NameError,FileNotFoundError): print("有异常请处理....") #except Exception: # print("如果用了Exception,那么意味着只要上面的except没有捕获到异常,这个except一定捕获到") #想看是什么异常用 as except Exception as result: print("如果用了Exception,那么意味着只要上面的except没有捕获到异常,这个except一定捕获到") print(result)#打印错误的类型 else: print("没有异常才会执行的功能...") finally: print("不管有没有异常我最后都执行finally...") print("----2----") # 运行结果 division by zero 不管有没有异常我最后都执行finally... ----2---- -
ctrl+c异常
import time while True: print("哈哈") time.sleep(1) # 运行结果 哈哈 哈哈 ^CTraceback (most recent call last): File "02-ctrl+c异常.py", line 5, in <module> time.sleep(1) KeyboardInterrupt -
异常的传递
def test1(): print("----test1----") print(num) #自己下面没有异常处理 把这个错误反回给调用处 print("----test1----") def test2(): print("----test2----") test1() # 这里也没有异常处理 把错误反回给调用处 print("----test2----") def test3(): try: print("----test3----") test2() # 这里有异常处理 直接处理 print("----test3----") except Exception as result: print("异常为:%s"%result) test3() print("-------华丽的切换-------") test2() #直接挂掉因为没有异常处理 # 运行结果 ----test3---- ----test2---- ----test1---- 异常为:name 'num' is not defined -------华丽的切换------- ----test2---- ----test1---- Traceback (most recent call last): File "03-异常的传递.py", line 21, in <module> test2() #直接挂掉因为没有异常处理 File "03-异常的传递.py", line 8, in test2 test1() # 这里也没有异常处理 把错误反回给调用处 File "03-异常的传递.py", line 3, in test1 print(num) #自己下面没有异常处理 把这个错误反回给调用处 NameError: name 'num' is not defined -
用户自定义异常-raise
class ShortInputException(Exception): '''自定义异常类''' def __init__(self,lenght,atleast): self.lenght = lenght self.atleast = atleast def main(): try: s = input("请输入:") if len(s) < 3: # raise 引发一个你定义的异常 raise ShortInputException(len(s),3) except ShortInputException as result: # result 这个变量被绑定到了错误的实列 print("ShortInputException:输入的长度:%d,长度至少应是:%d"%(result.lenght,result.atleast)) else: print("没有异常...") main() # 运行结果 请输入:1 ShortInputException:输入的长度:1,长度至少应是:3 -
异常处理中抛出异常
class Test(object): def __init__(self,switch): self.switch = switch def calc(self,a,b): try: return a/b except Exception as result: if self.switch: print("捕获开启,已经捕获到异常,信息如下...") print(result) else: #重新抛出异常,此时就不会被这个异常处理给捕获到,从而触发默认的异常处理 raise else: print("没有异常....") a = Test(True) a.calc(11,0) print("-----华丽的分割线-----") a.switch = False a.calc(11,0) # 运行结果 捕获开启,已经捕获到异常,信息如下... division by zero -----华丽的分割线----- Traceback (most recent call last): File "05-异常处理中抛出异常.py", line 23, in <module> a.calc(11,0) File "05-异常处理中抛出异常.py", line 8, in calc return a/b ZeroDivisionError: division by zero
浙公网安备 33010602011771号