ITeye博客

python教程:异常处理

fudehai001 · 2009-07-21 13:52 · python · Markdown

#例子1

  1. #coding:utf-8
    2.
    3. def fun(a, b):
    4. if b == 0:
    5. raise Exception('info', 'zero')
    6. else:
    7. return a / b
    8. i = 2
    9. while i > 0:
  2. try:  
    
  3.     k = 0  
    
  4.     n = 5 / k  
    
  5. except  KeyboardInterrupt:#键盘异常:ctr+ d可以推出循环  
    
  6.     break                 
    
  7. except Exception, e:      #异常对象  
    
  8.     print 'error', e      #输出异常信息  
    
  9. finally:  
    
  10.     'finally'  
    
  11. i -= 1  
    
  12. print 'end'
  13. print fun(1, 1)
  14. print fun(1, 0)

#-------------------------------------------

#例子2 #!/usr/bin/python

Filename: raising.py

class ShortInputException(Exception): '''A user-defined exception class.''' def init(self, length, atleast): Exception.init(self) self.length = length self.atleast = atleast

try: s = raw_input('Enter something --> ') if len(s) < 3: raise ShortInputException(len(s), 3) # Other work can continue as usual here except EOFError: print '\nWhy did you do an EOF on me?' except ShortInputException, x: print 'ShortInputException: The input was of length %d,
was expecting at least %d' % (x.length, x.atleast) else: print 'No exception was raised.'

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。