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
应用场景
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"
标准异常 & 自定义异常
自定义异常:
// 定义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) ##
原文链接
相关文章链接
阅读全文
0 0
- Python 异常处理 try/except
- python异常处理try...except
- Python 异常处理 Python 基础教程 try..except
- (Python)异常处理try...except、raise
- (Python)异常处理try...except、raise
- python中的异常处理 try..except
- Python异常处理try...except、raise
- Python---异常处理try...except、raise
- (Python)异常处理try...except、raise
- Python异常处理try...except、raise
- python try...except....else...finally处理异常
- Python 异常处理 (try 和 except)
- try,except异常处理
- Python 异常 try except
- Python3:异常处理,try...except
- 异常处理try...except、raise
- python 异常 try-except句型
- python 异常 try-except句型
- [leetcode-2] Add Two Numbers
- Netty in action—单元测试
- keil RT-Thread相关调试基本使用技巧
- 设计模式 -- 创建型模式
- webdriver Debug
- python异常处理try...except
- Ubuntu使用笔记
- 数据结构 之 循环队列
- 实现九宫格
- 实验报告一:写一个hello world小程序
- Android手机录制屏幕并转gif图
- 配置maven所需要的jar包
- Eclipse Debug 学习
- 欢迎使用CSDN-markdown编辑器