【脚本语言系列】关于Python异常处理,你需要知道的事
来源:互联网 发布:淘宝好评卡片 编辑:程序博客网 时间:2024/06/04 23:07
如何进行异常处理
Python异常类定义在exceptions模块中,并继承自基类BaseException.
BaseException类有三个子类,为Exception,KeyboardInterrupt,SystemExit.
Exception类是异常类,包括StandardError,StopIteration,GeneratorExit,Warning.
try…except语句用于处理问题语言,捕获可能出现的异常。
try…except
# -*- coding:utf-8 -*-# catch IOErrortry: file("hello.txt","r") print "read file"except IOError: print "File Not Exit"except: print "program abnormal"
read file
# -*- coding:utf-8 -*-# catch ZeroDivisionErrortry: result = 10/0except ZeroDivisionError: print "0 Division Error"
0 Division Error
# -*- coding:utf-8 -*-# catch ZeroDivisionErrortry: result = 10/0except ZeroDivisionError: print "0 Division Error"else: print result
0 Division Error
# -*- coding:utf-8 -*-# nest the Errortry: s = "hello" try: print s[0]+s[1] print s[0]-s[1] except TypeError: print "String not support -"except: print "Exception"
heString not support -
try…finally
# -*- coding:utf-8 -*-# try the finallytry: f = open("hello.txt","r") print "read file"except IOError: print "file not exist"finally: f.close()
read file
# -*- coding:utf-8 -*-# nest the finallytry: f = open("hello.txt","r") try: print f.read(5) except: print "read file Error" finally: print "release the src" f.close()except IOError: print "file not exist"
read file
raise
# -*- coding:utf-8 -*-# try the raisetry: s = None if s is None: print "s is empty object" raise NameError print len(s)except TypeError: print "Empty object has no length"
s is empty object---------------------------------------------------------------------------NameError Traceback (most recent call last)<ipython-input-10-084f89ed5ff6> in <module>() 5 if s is None: 6 print "s is empty object"----> 7 raise NameError 8 print len(s) 9 except TypeError:NameError:
自定义异常
# -*- coding:utf-8 -*-# self the exceptionfrom __future__ import divisionclass DivisionException(Exception): def __init__(self, x, y): Exception.__init__(self, x, y) self.x = x self.y = yif __name__ == "__main__": try: x = 7 y = 5 if x % y > 0: print x/y raise DivisionException(x, y) except DivisionException, div: print "DivisionException: x / y = %.2f" %(div.x/div.y)
1.4DivisionException: x / y = 1.40
assert
# -*- coding:utf-8 -*-# use the assertt = ("hello",)assert len(t) >= 1t = ("hello")assert len(t) == 1
---------------------------------------------------------------------------AssertionError Traceback (most recent call last)<ipython-input-13-e1aea18859ed> in <module>() 4 assert len(t) >= 1 5 t = ("hello")----> 6 assert len(t) == 1AssertionError:
# -*- coding:utf-8 -*-# use the assert with msgmonth = 13assert 1 <= month <= 12, "month errors"
---------------------------------------------------------------------------AssertionError Traceback (most recent call last)<ipython-input-21-4aeda76e0fa4> in <module>() 2 # use the assert with msg 3 month = 13----> 4 assert 1 <= month <= 12, "month errors"AssertionError: month errors
exception 异常信息
# -*- coding:utf-8 -*-def fun(): a = 10 b = 0 return a / bdef format(): print "a / b = " + str(fun())if __name__ == "__main__": format()
---------------------------------------------------------------------------ZeroDivisionError Traceback (most recent call last)<ipython-input-20-1916b966487f> in <module>() 9 10 if __name__ == "__main__":---> 11 format()<ipython-input-20-1916b966487f> in format() 6 7 def format():----> 8 print "a / b = " + str(fun()) 9 10 if __name__ == "__main__":<ipython-input-20-1916b966487f> in fun() 3 a = 10 4 b = 0----> 5 return a / b 6 7 def format():ZeroDivisionError: division by zero
# -*- coding:utf-8 -*-import systry: x = 10 / 0except Exception, ex: print exprint sys.exc_info()
division by zero(None, None, None)
什么是异常处理
异常是程序中的例外、违例情况。
异常机制是指当程序出现错误后,程序的处理方法,
异常机制提供了程序正常退出的安全通道。
当出现错误后,程序执行的流程发生改变,程序的控制权转移到异常处理器。
当异常被引发时,如果没有代码处理该异常,异常将被Python接受处理。
当异常发生时,Python解释器将输出一些相关的信息并终止程序的运行。
为何进行异常处理
通过捕获异常可以提高程序的健壮性。
异常处理还具有释放对象、中止循环的运行等作用。
阅读全文
0 0
- 【脚本语言系列】关于Python异常处理,你需要知道的事
- 【脚本语言系列】关于Python基础知识异常处理,你需要知道的事
- 【脚本语言系列】关于Python系统管理,你需要知道的事
- 【脚本语言系列】关于Python容器,你需要知道的事
- 【脚本语言系列】关于Python音频处理DirectSound, 你需要知道的事
- 【脚本语言系列】关于Python图像处理PIL,你需要知道的事
- 【脚本语言系列】关于Python数据库处理SQLite,你需要知道的事
- 【脚本语言系列】关于Python数据库处理MySQL, 你需要知道的事
- 【脚本语言系列】关于Python基础知识处理字符串,你需要知道的事
- 【脚本语言系列】关于Python数据库处理SQLite数据库,你需要知道的事
- 【脚本语言系列】关于Python数据库处理SQLAlchemy,你需要知道的事
- 【脚本语言系列】关于Python结构化文本文件处理YAML,你需要知道的事
- 【脚本语言系列】关于Python结构化文本文件处理csv,你需要知道的事
- 【脚本语言系列】关于Python结构化文本文件处理xml,你需要知道的事
- 【脚本语言系列】关于Python结构化文本文件处理HTML,你需要知道的事
- 【脚本语言系列】关于Python结构化文本文件处理JSON,你需要知道的事
- 【脚本语言系列】关于Python结构化文本文件处理配置文件.ini,你需要知道的事
- 【脚本语言系列】关于Python结构化文本文件处理MsgPack,你需要知道的事
- golang写入文件操作
- pat1061-1070
- 建立软件工程之动态模型(状态图)步骤
- 图片压缩上传
- 网络编程步骤
- 【脚本语言系列】关于Python异常处理,你需要知道的事
- codeforces 814A
- 2016百度-罪犯转移-Java
- java中volatile关键字的含义
- R语言使用merge函数匹配数据(vlookup,join)
- 漫谈Java理念的转变与JVM的五大优势
- 《演讲的力量》读书笔记
- keras系列︱迁移学习:利用InceptionV3进行fine-tuning及预测、完美案例(五)
- 逆向基础笔记