python学习笔记(异常)

什么是异常

python用异常对象(exception object)来表示异常情况。遇到错误后,会引发异常。如果异常对象并未被处理或捕捉,程序就会用所谓的 回溯(Traceback, 一种错误信息)终止执行

>>> 1/0

Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
1/0
ZeroDivisionError: integer division or modulo by zero
>>>

按自己的方式出错

raise语句

>>> raise Exception

Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
raise Exception
Exception
>>> raise Exception(‘hyperdrive overload‘)

Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
raise Exception(‘hyperdrive overload‘)
Exception: hyperdrive overload
>>>

查看exceptions模块中的内建异常

>>> import exceptions
>>> dir(exceptions)
[‘ArithmeticError‘, ‘AssertionError‘, ‘AttributeError‘, ‘BaseException‘, ‘BufferError‘, ‘BytesWarning‘, ‘DeprecationWarning‘, ‘EOFError‘, ‘EnvironmentError‘, ‘Exception‘, ‘FloatingPointError‘, ‘FutureWarning‘, ‘GeneratorExit‘, ‘IOError‘, ‘ImportError‘, ‘ImportWarning‘, ‘IndentationError‘, ‘IndexError‘, ‘KeyError‘, ‘KeyboardInterrupt‘, ‘LookupError‘, ‘MemoryError‘, ‘NameError‘, ‘NotImplementedError‘, ‘OSError‘, ‘OverflowError‘, ‘PendingDeprecationWarning‘, ‘ReferenceError‘, ‘RuntimeError‘, ‘RuntimeWarning‘, ‘StandardError‘, ‘StopIteration‘, ‘SyntaxError‘, ‘SyntaxWarning‘, ‘SystemError‘, ‘SystemExit‘, ‘TabError‘, ‘TypeError‘, ‘UnboundLocalError‘, ‘UnicodeDecodeError‘, ‘UnicodeEncodeError‘, ‘UnicodeError‘, ‘UnicodeTranslateError‘, ‘UnicodeWarning‘, ‘UserWarning‘, ‘ValueError‘, ‘Warning‘, ‘WindowsError‘, ‘ZeroDivisionError‘, ‘__doc__‘, ‘__name__‘, ‘__package__‘]
>>>

>>> raise ArithmeticError

Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
raise ArithmeticError
ArithmeticError
>>>

自定义异常类

尽管内建的异常类已经包括了大部分的情况,而且对于很多要求都已经足够了,但有些时候还是需要创建自己的异常类。

和常见其它类一样----只是要确保从Exception类继承,不管直接继承还是间接继承。像下面这样:

>>> class SomeCustomException(Exception):
pass

当然,也可以为这个类添加一些方法。

捕捉异常

我们可以使用 try/except 来实现异常的捕捉处理。

假设创建了一个让用户输入两个数,然后进行相除的程序:

x=input(‘Please enter the first number: ‘)
y=input(‘Please enter the second number: ‘)
print x/y

Please enter the first number: 10
Please enter the second number: 0

Traceback (most recent call last):
File "F:/python/myDemo/except.py", line 3, in <module>
print x/y
ZeroDivisionError: integer division or modulo by zero
>>>

为了捕捉异常并做出一些错误处理,可以这样写:

try:
x=input(‘Please enter the first number: ‘)
y=input(‘Please enter the second number: ‘)
print x/y
except ZeroDivisionError:
print ‘The second number can\‘t be zero‘

------------

Please enter the first number: 10
Please enter the second number: 0
The second number can‘t be zero
>>>

假如,我们在调试的时候引发异常会好些,如果在与用户的进行交互的过程中又是不希望用户看到异常信息的。那如何开启/关闭 “屏蔽”机制?

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

------------

>>> calculator=MuffledCalculator()
>>> calculator.calc(‘10/2‘)
5
>>> calculator.calc(‘10/0‘)

Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
calculator.calc(‘10/0‘)#没有屏蔽
File "F:/python/myDemo/except.py", line 5, in calc
return eval(expr)
File "<string>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> calculator.muffled=True
>>> calculator.calc(‘10/0‘)
Division by zero is illegal
>>>

不止一个except子句

如果运行上面的(输入两个数,求除法)程序,输入面的内容,就会产生另外一个异常:

enter the first number: 10
enter the second number: ‘hello,world‘

Traceback (most recent call last):
File "F:/python/myDemo/except.py", line 4, in <module>
print x/y
TypeError: unsupported operand type(s) for /: ‘int‘ and ‘str‘
>>>

因为except子句只检查ZeroDivisionError异常,所以这个异常就错过了检查,为了捕捉这个异常,我们可以在try/except语句加一个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: 10
enter the second number: ‘hello,world!‘
That wasn‘t a number,was it?
>>>

用一个块捕捉两个异常

try:
x=input(‘enter the first number: ‘)
y=input(‘enter the second number: ‘)
print x/y

捕捉对象

try:
x=input(‘enter the first number: ‘)
y=input(‘enter the second number: ‘)
print x/y
except (ZeroDivisionError,TypeError,NameError),e:
print e

-----------------

>>>
enter the first number: 10
enter the second number: 2
5
>>>
>>> ================================ RESTART ================================
>>>
enter the first number: 10
enter the second number: 0
integer division or modulo by zero
>>> ================================ RESTART ================================
>>>
enter the first number: 10
enter the second number: ‘hello,world‘
unsupported operand type(s) for /: ‘int‘ and ‘str‘
>>>

真正的全捕捉

就算程序能处理好几种异常,但有些异常还是会处理不到,例如上个除法的例子,输入空格:

enter the first number:

Traceback (most recent call last):
File "F:/python/myDemo/except.py", line 2, in <module>
x=input(‘enter the first number: ‘)
File "<string>", line 0

^
SyntaxError: unexpected EOF while parsing
>>>

因此我们可以在except子句中忽略所有异常类

try:
x=input(‘enter the first number: ‘)
y=input(‘enter the second number: ‘)
print x/y
except:
print ‘Something wrong happend...‘

--------------

>>>
enter the first number: 10
enter the second number: 0
Something wrong happend...
>>> ================================ RESTART ================================
>>>
enter the first number:
Something wrong happend...
>>>

万事大吉

while True:

try:
x=input(‘Enter the first number: ‘)
y=input(‘Enter the second number: ‘)
value=x/y
print ‘x/y is ‘,value
except:
print ‘Invalid input .Please try again.‘
else:
break

--------------------

Enter the first number: 10
Enter the second number: 0
Invalid input .Please try again.
Enter the first number: 10
Enter the second number: ‘hello‘
Invalid input .Please try again.
Enter the first number: 10
Enter the second number: 2
x/y is 5
>>>

最后

最后finally子句用来对可能的异常进行清理,它和try子句联合使用

x=None
try:
x=1/0
finally:
print ‘Cleaning up...‘
del x

-------------

Cleaning up...

Traceback (most recent call last):
File "F:/python/myDemo/except.py", line 3, in <module>
x=1/0
ZeroDivisionError: integer division or modulo by zero
>>>

try:
1/0
except NameError:
print ‘Unknown variable‘
else:
print ‘That went well!‘
finally:
print ‘Cleaning up.‘

异常和函数

如果异常在函数内没被处理,它就会传播至函数调用的地方,直到程序带着堆栈跟踪终止

def faulty():
raise Exception(‘Someting is wrong‘)
def ignore_exception():
faulty()
def handle_exception():
try:
faulty()
except:
print ‘Exception handled‘

----------------------------

>>> ignore_exception()

Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
ignore_exception()
File "F:/python/myDemo/except.py", line 4, in ignore_exception
faulty()
File "F:/python/myDemo/except.py", line 2, in faulty
raise Exception(‘Someting is wrong‘)
Exception: Someting is wrong
>>> handle_exception()
Exception handled
>>>

时间: 2024-08-02 17:14:16

python学习笔记(异常)的相关文章

Python学习笔记-异常

Python的运行时错误称为异常 1.语法错误:软件的结构上有错误而导致不能被解释器解释或不能被编译器编译. 2.逻辑错误:由于不完整或不合法的输入所致,也可能是逻辑无法生存.计算或者输出结果需要的过程无法执行等. Python异常是一个对象,表示错误或意外情况 在python检测到一个错误时,将触发一个异常 1.python可以通过异常传导机制传递一个异常对象,发出一个异常情况出现的信号 2. 程序员也可以在代码中手动触发异常 python异常也可以理解为:程序出现了错误而在正常控制流以外采取

Python学习笔记--未经排版

Python 学习笔记 Python中如何做到Print() 不换行 答:Print("输出内容",end='不换行的分隔内容'),其中end=后面为2个单引号 注:在Python 2.x中,Print "输出内容", 即在输出内容后加一逗号 Python中 is 和 == 的区别 答:Python中的对象包含三要素:id.type.value 其中id用来唯一标识一个对象,type标识对象的类型,value是对象的值 is判断的是a对象是否就是b对象,是通过id来

python 学习笔记 6 -- 异常处理

当你的程序中出现某些 异常的 状况的时候,异常就发生了.例如,当你想要读某个文件的时候,而那个文件不存在.或者在程序运行的时候,你不小心把它删除了. 那么如果你是在IDE中运行,一个错误发生,异常会被打引出来,这便是未处理异常:当异常发生时,如果没有代码去关注和处理它,这些异常会传给置在Python中的缺省处理,他会输出一些调试信息并且终止运行.如果是在IDE中,这不是什么大事,但是如果是Python程序运行中的异常,它会导致整个程序终止,对于这些情况可以使用异常来处理. 1.try..exce

python学习笔记十——异常处理

1.try: command except 错误类型,记录错误信息变量: command finally: command try...finally的用处是无论是否发生异常都要确保资源释放代码的执行.一般来说,如果没有发生错误,执行过try语句块之后执行finally语句块,完成整个流程.如果try语句块发生了异常,抛出了这个异常,此时就马上进入finally语句块进行资源释放处理.如下从几个细节讨论finally的特性. 1).try中的return: 当在try语句块中含有return语句

雨痕 的《Python学习笔记》--附脑图(转)

原文:http://www.pythoner.com/148.html 近日,在某微博上看到有人推荐了 雨痕 的<Python学习笔记>,从github上下载下来看了下,确实很不错. 注意,这本学习笔记不适合Python新手学习. 从目录上看,并不能看出这本笔记有何特别之处,但看到里面的内容,感到非常惊喜.这本书更多的是关注一些底层的实现细节,以及更多的考虑性能方面(讲解内容很多会涉及到内存管理.缓存.垃圾回收.堆栈帧等方面的内容). 目前本笔记的最近更新时间为2013.03.30.大家可以到

01-Python学习笔记-基础语法

Python标识符 -d           在解析时显示调试信息 -O           生成优化代码 ( .pyo 文件 ) -S           启动时不引入查找Python路径的位置 -v            输出Python版本号 -X           从 1.6版本之后基于内建的异常(仅仅用于字符串)已过时. -c cmd     执行 Python 脚本,并将运行结果作为 cmd 字符串. file           在给定的python文件执行python脚本. P

python 学习笔记 7 -- Python关键字总结

0.写在前面的话 学习一门语言最重要的功课是练习与复习,在<笨方法学Python>中第三十七节虽然没有教你任何内容,但是它提醒我们:"学了这么多,你还能记得多少?该复习了!" 下面我们就对这一节的第一部分"关键字"来做个复习: Python中的关键字包括如下: and       del        from      not      while    as        elif       global    or       with     

【Python学习笔记之二】浅谈Python的yield用法

在上篇[Python学习笔记之一]Python关键字及其总结中我提到了yield,本篇文章我将会重点说明yield的用法 在介绍yield前有必要先说明下Python中的迭代器(iterator)和生成器(constructor). 一.迭代器(iterator) 在Python中,for循环可以用于Python中的任何类型,包括列表.元祖等等,实际上,for循环可用于任何“可迭代对象”,这其实就是迭代器 迭代器是一个实现了迭代器协议的对象,Python中的迭代器协议就是有next方法的对象会前

【Python学习笔记】集合

概述 集合的一般操作 内建函数进行标准操作集合 数学运算符进行标准操作集合 集合的应用 概述 python的集合(set)是无序不重复元素集,是一种容器.集合(set)中的元素必须是不可变对象,即可用被哈希,这和字典的键是一样的,所以列表.字典等可变对象不可作为set的元素.集合不提供索引或切片操作,即对象不存在相关的键值.python中的集合分为两种:set是可变的集合,frozenset是不可变的集合. 集合的创建使用关键字set或frozenset, 参数可以是列表.字符串或元组等不可变对

python &nbsp; 学习笔记 (核心)

python    学习笔记 (核心) Python解释器从头到尾一行接一行执行脚本 # -*- coding: UTF-8 -*-    //字符编码 不区分单引号和双引号,x='hello',x[0],x[-1]指最后一个字符,x[2:4]取子串, '''hello''' #hello三引号会保留文本输入时的换行符制表符等不需要转义,用于多行原样输入保存 'hello'+'world' #字符串拼接,'hello'*2 #字符串重复 help(fun) #帮助,help(module.met