免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2426 | 回复: 0

Python 语法之例外 [复制链接]

论坛徽章:
0
发表于 2009-10-24 16:53 |显示全部楼层


  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
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP