python异常处理try...except

来源:互联网 发布:MySQL 转为percona 编辑:程序博客网 时间:2024/05/18 05:34

常见错误


(1)NameError:命名错误

(2)SyntaxError:语法错误

(3)IOError:IO错误

(4)ZeroDivisionError:除0错误

(5)ValueError:值错误

(6)KeyboardInterrupt:用户干扰退出

try & execpt


# try -> else -> finallytry:      try_suiteexcept IOError, e:      do_exceptexcept ValueError, e:      do_exceptelse:    do_elsefinally:    do_finally

with as


with语句实质上是上下文管理

理论知识

上下文管理协议:包含方法:__enter__(),__exit()__

需要注意的是,with语句代码段中,如果出现了异常,那么将无法保证with语句一定能将file关闭。

 try:      with open(‘test.txt’, ‘r’) as f:            f.seek(-1, os.SEEKSET)  # 此处会报错,代码意思是找到了文件头部之后的-1的位置,显然不存在。except ValueError,e:          handle_except
# 当代码中使用了try-except后,那么with语句在先将文件关闭后,再将error抛出,截获后再对error进行处理。

应用场景

1.文件操作;2.进程线程之间互斥对象,例如互斥锁;3.支持上下文的其他对象。

raise & assert


raise XXError(“ErrorInfo”) // python3以后的写法
raise XXError. “ErrorInfo” // python2中的写法,但在2中也支持上面的写法

raise NameError('HiThere')    Traceback (most recent call last):     File "<stdin>", line 1, in     NameError: HiThere

assert语句
断言语句:assert语句用于检测表达式是否为真,如果为假,引发AssertionError错误;

assert exception, "errorInfo"

标准异常 & 自定义异常



Paste_Image.png

自定义异常:

// 定义class FileError(IOError):      pass// 触发异常assert FileError, "file Error!"try:     raise FileError, "Test FileError"except FileError, e:     print(e)
class CustomError(Exception):      def __init__(self, info):            Exception.__init__(self)   # 重写父类方法            self.errorinfo = info      def __str__(self):            return "CustionError:%s" % self.errorinfotry :      raise CustomError("test CustomError")except CustomError, e:      print(e)   ##

原文链接
相关文章链接

原创粉丝点击