码迷,mamicode.com
首页 > 编程语言 > 详细

python学习_26(异常)

时间:2018-11-13 17:14:51      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:注意   2.3   一个   ror   文件   没有   嵌套   erro   code   

异常: try: <语句>#可能发生异常的代码 except<名字>: <语句>#如果在try部份引发了‘name‘异常 except<名字> as <异常参数>: <语句>#如果引发了‘name’异常,获得附加的异常对象 else: <语句>#如果没有异常发生 finally: <语句>#始终都会执行的语句 嵌套异常捕获 try: try: 1/0 except IOError: print("IOError ") except Exception as e: print(e) except不携带任何异常类型 try: int("2.3") except: print("error") else: print("no error") except携带多种异常类型 需要用括号 try: int("2.3") except (ValueError,TypeError) as e: print(e) else: print("no error") 多个except try: int("2.3") except ValueError as e: print(e) except TypeError as e: print(e) except Exception as e: print(e) else: print("no error") try-finally try: fp = open("e:\\1e.txt") try: content = fp.read() print(content) finally: print("关闭文件") fp.close() except IOError: print("没有找到文件") 文件存在 文件不存在 try-else try: fp = open("e:\\e.txt") try: content = fp.read() print(content) finally: print("关闭文件") fp.close() except IOError: print("没有找到文件") else: print("找到了文件") try-except-else-finally finally需要放到else的后面 try: fp = open("e:\\e.txt") try: content = fp.read() print(content) finally: print("关闭文件") fp.close() except IOError: print("没有找到文件") else: print("找到了文件") finally: print("finally 始终都会执行") 异常可携带参数e import traceback try: fp = open("e:\\eeeee.txt") except IOError as e: print(e) print(traceback.print_exc()) else: print("找到了文件") 主动抛出异常raise #encoding=utf-8 def div(a,b): if b == 0: raise Exception("除数为0") else: return a/b if __name__ == "__main__": try: res = div(2,0) except Exception as e: print(e) else: print(res) 自定义异常 #encoding=utf-8 class MyException(Exception): def __init__(self,value): self.value = value if __name__ == "__main__": try: raise MyException("自定义异常信息") except MyException as e: print("捕获自定义异常",e.value) #coding=utf-8 class ShortInputException(Exception): ‘‘‘A user-defined exception class.‘‘‘ def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleast try: s = input(‘Enter something --> ‘) if len(s) < 3: #如果输入的内容长度小于3,触发异常 raise ShortInputException(len(s), 3) except EOFError: print (‘\nWhy did you do an EOF on me?‘) except ShortInputException as x: print (‘ShortInputException: The input was of length %d, was expecting at least %d‘ % (x.length, x.atleast)) else: print (‘No exception was raised.‘) 异常抛出机制: 1、如果在运行时发生异常,解释器会查找相应的处理语句(称为handler)。 2、要是在当前函数里没有找到的话,它会将异常传递给上层的调用函数,看看 那里能不能处理。 3、如果在最外层(全局“main”)还是没有找到的话,解释器就会退出,同时打印 出traceback以便让用户找到错误产生的原因。 注意: 虽然大多数错误会导致异常,但一个异常不一定代表错误,有时候它们只是一个 警告,有时候它们可能是一个终止信号,比如退出循环等

python学习_26(异常)

标签:注意   2.3   一个   ror   文件   没有   嵌套   erro   code   

原文地址:http://blog.51cto.com/13496943/2316455

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!