Python学習ノート(八)——Python異常処理

2843 ワード

1、異常モジュール
#-*- coding: utf-8 -*-
import exceptions
#dir         
print dir(exceptions)  #['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__doc__', '__name__', '__package__']

2、異常の作成
#     class   Exception  
class SomeException(Exception):pass

3、捕獲異常
異常
#      try/except      
try:
    x=input("num1:") #raw_input()      str   ,input       int
    y=input("num2:")
    print x/y  
except ZeroDivisionError:
    print "y=0!"   #y=0!

例外オブジェクトのキャプチャ
#      
try:
    x=input("num1:")  
    y=input("num2:")
    print x/y  
# except (ZeroDivisionError,TypeError),e:
#     print e #integer division or modulo by zero
#    
except Exception,e:
    print e #integer division or modulo by zero
finally:
    print 'OVER'

異常捕獲ゴールドコーディネート:try/except/else/finally
4、クラス定義方法における異常のキャプチャ
#class       try/except
class Calculate:
    muffled=True
    def cal(self,expr):
        try:
            return eval(expr)
        except ZeroDivisionError:
            if self.muffled:  #True 10/0   Division is O 
                print "Division is O"
            else:    #False 10/0     raise   ZeroDivisionError
                raise
        else:
            print "money"    
#  
ca=Calculate()
print ca.cal('10/0')

5、異常を起こす
#    
raise ArithmeticError

6、異常関数の定義
#    
def faulty():
    raise Exception("sth is wrong")

faulty() #        ,Exception: sth is wrong