#coding=utf-8
#
# 异常
#
#8-1 什么是异常
# print 1/0 # 导致系统崩溃
#8-2 预防异常
#查看异常 接口
import exceptions
print dir(exceptions)
#raise 语句
#raise Exception # 直接显示异常
#raise Exception('here is error') # 打印异常信息
#raise ArithmeticError
#8-3捕捉异常
try:
print 1/0
except ZeroDivisionError: # ZeroDivisionError 内建异常函数; (除0错误) 的情况
print 'error:num is zero'
#屏蔽异常
class TestError:
isClose = False
def calc(self, expr):
try:
return eval(expr) #u'运行字符串命令'
except (ZeroDivisionError,), test: # test 捕捉; 错误信息
if self.isClose:
print 'show error msg',test
else:
raise # 会调用 ZeroDivisionError
except TypeError: # 可以监听多个异常
print 'it\'s not num'
except NameError:
print 'name'
ep = TestError()
print ep.calc('10/2')
ep.isClose = True # 屏蔽 ,使程序 能够运行下去不崩溃
print ep.calc('10/0')
print ep.calc('10/qwer')
# 多个异常
class _TestError:
isClose = False
def calc(self, expr):
try:
return eval(expr)
except (ZeroDivisionError, TypeError, NameError): #放置在括号内 , 用作元组
if self.isClose:
print 'show error msg'
else:
raise
#8-4异常忽略
try:
print 1/0
except:
print 'something error'
#8-8 转折 else
try:
pass
except:
print 'error'
else:
print 'else ' # 用于循环检查 异常时, else 可以做 break 处理
#ep
while True:
try:
x = raw_input("input x:")
y = raw_input("input y :")
print int(x)/int(y)
except:
print 'error'
else:
break
#8-9 finally异常后清理
try:
x = 1/0
except:
print 'error'
finally:
print 'Clean up'
del x
#8-10 异常 代替 条件判断
self_str = {'hello': 'world'}
if 'Hello' in self_str:
print self_str['Hello']
else:
print "error"
# 等同如下
try:
print self_str['Hello']
except:
print 'class errror'