九、python中的异常处理
1 异常
当读取一个文件,这个文件并不存在时候,会引发异常,类似的,还有很多异常的情况。
2 简单的异常测试代码
#此处在shell中运行。
>>> s = input('Enter something --> ')
Enter something -->
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
s = input('Enter something --> ')
EOFError: EOF when reading a line
>>>
3 通过try except处理异常
#输入15 Enter something --> 15 You entered 15 #输入ctrl+D Enter something --> ^D Why did you do an EOF on me? 按住ctrl+C Enter something --> You cancelled the operation.
4 自定义异常类抛出异常
# encoding=UTF-8 class ShortInputException(Exception): '''一个由用户定义的异常类''' def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleast try: 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 输入ha Enter something --> ha ShortInputException: The input was 2 long, expected at least 3 2 输入haha Enter something --> haha No exception was raised. 3 输入ctrl+c EOFError: 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 world haha
参考:《byte-of-python-chinese-edition》