Exception
来源:互联网 发布:银联数据公司员工跳槽 编辑:程序博客网 时间:2024/06/11 13:23
try..exception的写法如下所示,当文件不存在的时候出现error,输入错误信息
当文件存在时,执行else语句,关闭文件。不管OK还是NG都会执行finally语句。
import sys try: f = open("mfile.txt") except IOError as e: print("NO mfile.txt") print("system error message is :{0}".format(e)) else: print("close mfile") f.close()finally:print("finally")
Exception有个特殊tuple属性args用来存储参数,同样默认的__str__也是用的参数,所以在有参数并且没有定义__str__的Exception中,直接打印对象和args是相同的。
try:raise Exception('spam', 'eggs')except Exception as e:print(type(e))print(e.args)print(e)#输出结果为<class 'Exception'>('spam', 'eggs')('spam', 'eggs')
自定义Exception
class MyError(Exception):def __init__(self, myarg):self.myarg = myargdef __str__(self):return self.myargif __name__ == "__main__":try:raise MyError("my error")except MyError as e:print(e.args)print(e)# 输出结果# ('my error',)# my error
Python的内置异常类的继承关系如下所示
BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- ArithmeticError | +-- FloatingPointError | +-- OverflowError | +-- ZeroDivisionError +-- AssertionError +-- AttributeError +-- BufferError +-- EOFError +-- ImportError +-- LookupError | +-- IndexError | +-- KeyError +-- MemoryError +-- NameError | +-- UnboundLocalError +-- OSError | +-- BlockingIOError | +-- ChildProcessError | +-- ConnectionError | | +-- BrokenPipeError | | +-- ConnectionAbortedError | | +-- ConnectionRefusedError | | +-- ConnectionResetError | +-- FileExistsError | +-- FileNotFoundError | +-- InterruptedError | +-- IsADirectoryError | +-- NotADirectoryError | +-- PermissionError | +-- ProcessLookupError | +-- TimeoutError +-- ReferenceError +-- RuntimeError | +-- NotImplementedError +-- SyntaxError | +-- IndentationError | +-- TabError +-- SystemError +-- TypeError +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning +-- ImportWarning +-- UnicodeWarning +-- BytesWarning +-- ResourceWarning
<完>
0 0
- Exception
- Exception
- Exception
- exception
- Exception
- Exception
- Exception
- exception
- Exception
- Exception
- Exception
- Exception
- exception
- exception
- exception
- Exception
- Exception
- Exception
- Android 通知栏Notification的整合 全面学习 (一个DEMO让你完全了解它)
- 开关抖动延时
- 12周 老师兼干部类
- 网新恒天招聘会笔试题
- 设计模式13--观察者模式(Observer)
- Exception
- 第 7 章内存管理索引
- 转:关于el的详解
- Linux内核的配置编译与安装
- 《老罗Android》学习之 HTTP编程(一)
- 第十二周 项目3--摩托车继承自行车和机动车
- hdu 4804 Campus Design(插头dp)
- [BASIC-12] 十六进制转八进制
- Android-Universal-Image-Loader 图片异步加载类库的使用(超详细配置)