- 论坛徽章:
- 0
|
Normal
0
7.8 磅
0
2
false
false
false
EN-US
ZH-CN
X-NONE
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:普通表格;
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:"";
mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
mso-para-margin:0cm;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.5pt;
mso-bidi-font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-font-kerning:1.0pt;}
Python 语法之例外
File information
2009-10-24
磁针石:xurongzhong#gmail.com
博客:
oychw.cublog.cn
参考资料:
《Python Essential Reference 4th
Edition 2009》
《beginning python from novice to
professional second edition 2008》
exception objects
产生例外:raise Exception,raise
Exception('hyperdrive overload'),raise
RuntimeError("Unrecoverable Error")
查看例外种类: import exceptions 然后再:dir(exceptions),可以直接调用这些例外种类,比如:raise ArithmeticError。
重要的例外种类:Exception、AttributeError、IOError、IndexError、KeyError、NameError、SyntaxError、TypeError、ValueError、ZeroDivisionError
如果需要没有捕捉到的例外,可以送到sys.excepthook()
内置例外见参考1:87页
自定义例外类:
class
SomeCustomException(Exception): pass
class DeviceError(Exception):
def __init__(self,errno,msg):
self.args = (errno, msg)
self.errno = errno
self.errmsg = msg
# Raises an exception (multiple
arguments)
raise DeviceError(1, 'Not
Responding')
获取例外
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!"
也可以用if语句来判断,不过如果有多个分母,一个try就可以搞定了。
在没有交互式的情况,使用print更好,比如记录在日志中:
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
同时捕捉多个错误,上面的例子中,如果输入数字改用字符串则会报类型不匹配
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?"
多个例外也可以放在一个子句:
try:
x = input('Enter the first number:
')
y = input('Enter the second
number: ')
print x/y
except (ZeroDivisionError,
TypeError, NameError):
print 'Your numbers were bogus...'
捕捉对象,比如用log记录例外:
try:
x = input('Enter the first number:
')
y = input('Enter the second
number: ')
print x/y
except (ZeroDivisionError,
TypeError) as e:
print e
try:
do something
except:
error_log.write('An error
occurred\n')
捕捉所有错误:
try:
x = input('Enter the first number:
')
y = input('Enter the second
number: ')
print x/y
except:
print 'Something wrong
happened...'
一般不建议使用,可能会隐藏错误。
try也可以跟else:
try:
f = open('foo', 'r')
except IOError as e:
error_log.write('Unable to open
foo : %s\n' % e)
else:
data = f.read()
f.close()
修改上面程序直至输入正确:
while True:
try:
x = input('Enter the first number:
')
y = input('Enter the second
number: ')
value = x/y
print 'x/y is', value
except Exception, e:
print 'Invalid input:', e
print 'Please try again'
else:
break
最后还有finally可以用来收尾,比如关闭文件等。
try:
1/0
except NameError:
print "Unknown variable"
else:
print "That went well!"
finally:
print "Cleaning up."
例外不处理会累积至上级调用,直至处理为止。到最高层还不处理,会导致运行停止。
普通语句处理与例外处理:
if语句
def describePerson(person):
print 'Description of',
person['name']
print 'Age:', person['age']
if 'occupation' in person:
print 'Occupation:',
person['occupation']
例外:
def describePerson(person):
print 'Description of',
person['name']
print 'Age:', person['age']
try:
print 'Occupation: ' +
person['occupation']
except KeyError: pass
可以if语句处理要先检查是否有这个元素,再读取。例外处理有效一点,但不会特别明显。try/except和if/else有很大的相似性。
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/21908/showart_2077458.html |
|