python之异常处理

简单异常处理 

try:
    v = 2 / 0
except:
    print ( "got a exception")

 

 

异常嵌套

try:
    try:
        v2 = 2 * spam
    except:
        #print( "got spame exception" )
    v1 = 1 / 0

except ZeroDivisionError as a:
    print( "got a exception: " + str( a ) )
    try:
        v1 = 1 / 0
    except:
        print( "got annother exception" )

finally:
    print( "this is last clause" )

 

异常分类处理

BaseException为最基础的异常类型

try:
    v1 = 1 / 0
    v2 = 3 * spam
    v3 = '2' + 3
except TypeError as e:
    print( "got a type exception" )    
except NameError as e:
    print( "got a name exception" )
except Exception as e:
    print( "got a exception" )

打印异常的消息

try:
    v1 = 1 / 0
    v2 = 3 * spam
    v3 = '2' + 3
except Exception as e:
    print e.message

 

自定义异常以及使用raise抛出异常

class MyException(Exception):
    def __init__( self ):
        pass
    def __str__( self ):
        return str( "my exception ahs raised" )
    

try:
    raise MyException()
except MyException:
    print( "my exception error" )
except:
    print( "got a exception" )

所有的内置的异常类型以及继承关系请参看

http://docs.python.org/library/exceptions.html

 

 

版权所有,禁止转载. 如需转载,请先征得博主的同意,并且表明文章出处,否则按侵权处理.

    分享到:

留言

你的邮箱是保密的 必填的信息用*表示