異常try,raise----まとめ

1035 ワード

一)異常捕捉tryの定義:
try:
    pass  #         
except     1:
    pass  #       
except (    2,     3):
    pass   #       
except Exception as result:
    print(result)   #      
else:
    pass  #        
finally:
    pass   #        ,    。
    

二)異常捕捉の特性---異常は伝達行を有するので、一般的に主関数で異常を捕捉する.他の関数でビジネスロジックを重点的に処理します.これにより,コードに大量の異常キャプチャを追加する必要がなく,コードのクリーン性を保証できる.
def fun1():
    value = int(input('please enter a int:'))
    return value

def fun2():
    return fun1()

try:
    print(fun2())
except Exception as result:
    print("    :%s" % result)

三)自発放出異常raisepythonにはexceptionクラスが用意されており、特有の業務ニーズに応じて自発放出異常を設定できる1)異常exceptionクラスを作成する2)raiseキーワードを用いて異常を放出する
eg:
def set_passwd():
    pwd = input("please enter the password:")

    if len(pwd) >= 8:
        return pwd
    
    ex = Exception('the longth of pwd is not enough!')
    raise ex

try:
    print(set_passwd())
except Exception as result:
    print(result)