#coding:utf-8
'''
用途:
接收用户输出的参数,如果参数长度小于3,则抛出异常;如果参数中包含英文中的句号,则抛出相应的异常
否则,输出参数中各个字符对应的ascii码值
'''
import sys
class lengthlimit:
def __init__(self,length,atleast):
self.length = length
self.atleast= atleast
class translation:
def __init__(self,chars,tag='.'):
self.tag=tag
self.chars=chars
def toTrans(self):
print '*'*10+"Arguments:"+self.chars+"*"*10
for char in self.chars:
print "char:"+char+"====>","num:"+str(ord(char))
print
def getargv(i):
try:
if len(i) <3:
raise lengthlimit(len(i),3)
elif '.' in i:
raise translation(i)
except lengthlimit,e:
print 'curent length is:%d,%d required' %(e.length,e.atleast)
print
print '*'*5+"Raise Exception again"+"*" * 5
print
raise
except translation,e:
print "find '.' in %s,this is refused." % i
print
print '*'*5+"Raise Exception again"+"*" * 5
print
raise
#处理其他异常
except Exception,e:
raise
#如果没有引发异常,则输出各个字符的ascii码值
else:
t = translation(i)
t.toTrans()
if __name__=="__main__":
for i in sys.argv[1:]:
getargv(i)
用户自定义异常也可以是类。利用这个机制可以创建可扩展的异常体系。
以下是两种新的有效(语义上的)异常抛出形式:
raise Class, instance raise instance
raise instance # 自定义的异常类,raise 引发的实际是类的实例对象