1 异常
当读取一个文件,这个文件并不存在时候,会引发异常,类似的,还有很多异常的情况。
2 简单的异常测试代码
#此处在shell中运行。>>> s = input('Enter something --> ') Enter something --> Traceback (most recent call last): File "", line 1, in s = input('Enter something --> ') EOFError: EOF when reading a line >>>
3 通过try except处理异常
#输入15Enter something --> 15You entered 15#输入ctrl+DEnter something --> ^DWhy did you do an EOF on me?按住ctrl+CEnter something -->You cancelled the operation.
4 自定义异常类抛出异常
# encoding=UTF-8class ShortInputException(Exception): '''一个由用户定义的异常类''' def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleasttry: text = input('Enter something --> ') if len(text) < 3: raise ShortInputException(len(text), 3)# 其他工作能在此处继续正常运行except EOFError: print('Why did you do an EOF on me?')except ShortInputException as ex: print(('ShortInputException: The input was ' + '{0} long, expected at least {1}') .format(ex.length, ex.atleast))else: print('No exception was raised.')#结果1 输入haEnter something --> haShortInputException: The input was 2 long, expected at least 32 输入hahaEnter something --> hahaNo exception was raised.3 输入ctrl+cEOFError: EOF when reading a line
5 with语句的用法
在 try 块中获取资源,然后在 finally 块中释放资源是一种常见的模式。因此,还有一个with 语句使得这一过程可以以一种干净的姿态得以完成。 代码如下:
with open("poem.txt") as f: for line in f: print(line, end='')#结果 注意,源码文件和poem.txt文件在同一目录下hello worldhaha
参考:《byte-of-python-chinese-edition》