python学习笔记——第八章 异常
2014-05-08 21:44
731 查看
第八章 异常
1、捕捉异常:用try/except来实现
捕捉异常并重新引发---用raise实现
多个except,捕捉多个不同类型的异常
用一个块捕捉两个异常
捕捉对象---想让程序继续运行,又想记录错误时应用
捕捉所有的异常,except后不加东西
#try/except/else情况:
# try/except Exception,e /else
# try/finally
# try/except/else/finally (可以用其中3个组合)
异常和函数
查看对象是否存在特定特性时,try/except很有用
1、捕捉异常:用try/except来实现
>>> try: x = input('Enter the first number: ') y = input('Enter the second number: ') print(int(x)/int(y)) #需要转换为整型 except ZeroDivisionError: print("The second number can't be zero!") Enter the first number: 10 Enter the second number: 0 The second number can't be zero!
捕捉异常并重新引发---用raise实现
>>> class MuffledCalculator: muffled = False #屏蔽开关的标志 def calc(self,expr): try: return eval(expr) except ZeroDivisionError: if self.muffled: #若屏蔽开着,则捕捉异常并进行处理 print('Division by zero is illegal') else: #若屏蔽关着,则捕捉异常并重新引发 raise #except捕捉到了异常,raise重新引发异常 >>> >>> calculator = MuffledCalculator() >>> calculator.calc('10/2') 5.0 >>> calculator.calc('10/0') #屏蔽机制未打开,因为muffled = False Traceback (most recent call last): File "<pyshell#31>", line 1, in <module> calculator.calc('10/0') #屏蔽机制未打开,因为muffled = False File "<pyshell#27>", line 5, in calc return eval(expr) File "<string>", line 1, in <module> ZeroDivisionError: int division or modulo by zero >>> calculator.muffled = True #打开屏蔽机制 >>> calculator.calc('10/0') Division by zero is illegal
多个except,捕捉多个不同类型的异常
>>> try: x = input('Enter the first number: ') y = input('Enter the second number: ') print(x/y) except ZeroDivisionError: print("The second number can't be zero!") except TypeError: print("That wasn't a number. was it? ") Enter the first number: 2 Enter the second number: wsf That wasn't a number. was it?
用一个块捕捉两个异常
>>> try: x = input('Enter the first number: ') y = input('Enter the second number: ') print(x/y) except(ZeroDivisionError,TypeError,NameErrror): #NameError找不到名字(变量)时引发 print('Your numbers were bogus....')
捕捉对象---想让程序继续运行,又想记录错误时应用
>>> try: x = input('Enter the first number: ') y = input('Enter the second number: ') print(x/y) except (ZeroDivisionError, TypeError) as e: #python3.0中的写法 print(e) Enter the first number: 1 Enter the second number: 0 unsupported operand type(s) for /: 'str' and 'str'
捕捉所有的异常,except后不加东西
>>> try: x = input('Enter the first number: ') y = input('Enter the second number: ') print(x/y) except: print('Something wrong happened...') Enter the first number: "This" is "completely" illegal 123\ Enter the second number: 2 Something wrong happened...
#try/except/else情况:
>>> try: print('A simple task') except: print('What? Something went wrong?') else: print('Ah...It went as planned.') A simple task Ah...It went as planned. >>> while True: try: x = input('Enter the first number: ') y = input('Enter the second number: ') value = int(x)/int(y) print('x/y is', value) except: print('Invalid input, Please try again.') else: break Enter the first number: test Enter the second number: 1 Invalid input, Please try again. Enter the first number: 10 Enter the second number: 2 x/y is 5.0
# try/except Exception,e /else
>>> while True: try: x = input('Enter the first number: ') y = input('Enter the second number: ') value = int(x)/int(y) print('x/y is', value) except Exception as e: #python 3.0的写法 print('Invalid input: ',e) print('Please try again') else: break Enter the first number: 1 Enter the second number: 0 Invalid input: int division or modulo by zero Please try again Enter the first number: 'x' Enter the second number: 'y' Invalid input: invalid literal for int() with base 10: "'x'" Please try again Enter the first number: quux Enter the second number: 2 Invalid input: invalid literal for int() with base 10: 'quux' Please try again Enter the first number: 10 Enter the second number: 2 x/y is 5.0
# try/finally
>>> try: x = 1/0 finally: #finally子句肯定会被执行 print('Cleaning up...') del x Cleaning up... Traceback (most recent call last): File "<pyshell#25>", line 2, in <module> x = 1/0 ZeroDivisionError: int division or modulo by zero
# try/except/else/finally (可以用其中3个组合)
>>> try: 1/0 except NameError: print("Unknown variable") else: print("That went well!") finally: print("Cleaning up.")
异常和函数
>>> def describePerson(Person): print('Description of', person['name']) print('Age:', Person['age']) try: print('Occupation:' + person['occupation']) #打印职业时使用加号而不是逗号,否则字符串'Occupation:'在异常引发之前就会被输出 except KeyError: #键不存在 pass >>> person = {'name': 'Jack', 'age': 34} >>> describePerson(person) Description of Jack Age: 34 #如果最后一句为print 'Occupation:', person['occupation'] #则出现 >>> describePerson(person) Description of Sun Age: 32 Occupation: #所以要用加号连接,不用逗号,防止在异常发生前就被打印。
查看对象是否存在特定特性时,try/except很有用
>>> try: obj.write except AttributeError: print('The Object is not writeable') else: print('The Object is writeable')
相关文章推荐
- [Python学习笔记][第八章Python异常处理结构与程序调试]
- [Python学习笔记][第八章Python异常处理结构与程序调试]
- python基础教程_学习笔记10:异常
- python 对异常的处理(try...finally...和with 方法)- 千月的python linux 系统管理指南学习笔记(15)
- python 学习笔记8-----异常
- Python学习笔记--异常处理
- Python学习笔记(10):异常
- python学习笔记(九)异常处理
- Python学习笔记(八)异常
- python学习笔记——8_异常
- Python学习笔记之错误处理(关键词:错误处理、异常机制、try、except、else、finally、raise)
- Python 学习笔记 - 13.异常(Exception)
- Python学习笔记总结(四)异常处理
- python学习笔记(六)文件夹遍历,异常处理
- Python中的异常处理学习笔记
- Python学习笔记整理(十七)异常处理
- Python学习笔记:异常
- Python学习笔记——异常