Python学习笔记(八)——Python 异常处理

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

 

你可能感兴趣的:(【Python】)