分类: Python/Ruby
2009-10-24 16:53:16
Python 语法之例外
2009-10-24
磁针石:xurongzhong#gmail.com
参考资料:
《Python Essential Reference 4th
Edition 2009》
《beginning python from novice to
professional second edition 2008》
产生例外: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有很大的相似性。