python exception异常处理

Python异常处理格式:
try:
     Normal execution block

except A:
     Exception A handle

except B:
     Exception B handle

except:
     Other exception handle

else:
     if no exception,get here
finally:
     print("finally")

各种例子:

# except不指定异常,捕获所有异常
    try:
        1/0
    except:
        print "it is fault 1"
    
    # 执行else语句    
    try:
        0/1
    except:
        print "it is fault 2"
    else:
        print 'continue'
        
    
    
    # 执行finally语句
    f = None    
    try:
        #确保文件存在
        f = open("c:/reg.py")
        print "step 1"
    except:
        print "can not find file"
    else:
        print "step 2"
    finally:
        print "step 3 关闭文件"
        if f is not None:
            f.close()
    
    
    #捕获指定异常(ZeroDivisionError)
    a, b = (1, 0)
    try:
        a/b
    except ZeroDivisionError:
        print "b = 0, it is fault1."
    except Exception:
        print "haha exception"
        
        
    #捕获指定异常(ZeroDivisionError)
    a, b = (1, 0)
    try:
        a/b
    except (ZeroDivisionError, Exception):
        print "b = 0, it is fault2."
    
    
    # 普通的类也可以当异常处理
    class B:
        pass
    class C(B):
        pass
    class D(C):
        pass

    for c in [B, C, D]:
        try:
            raise c()
        except D:
            print "D"
        except C:
            print "C"
        except B:
            print "B"
    
    
    # 把异常传到外面去
    a, b = (1, 0)
    try:
        a/b
    except:
        print "把错误抛出去"
        raise

另外三个例子:

 
    a, b = (1, 0)
    try:
        a/b
    except (ZeroDivisionError, Exception) as e:
        # <type 'exceptions.ZeroDivisionError'>
        print type(e)
        
        
    a, b = (1, 0)    
    try:
        a/b
    except Exception as e:
        # <type 'exceptions.ZeroDivisionError'>
        print type(e)
        
        
    a, b = (1, 0)    
    try:
        a/b
    except Exception, e:
        #<type 'exceptions.ZeroDivisionError'>
        print type(e)
此条目发表在IT分类目录,贴了, , 标签。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。

*