定量的取引Pythonの基本-日常的な例外処理、関数での例外の積極的なスロー

#一般的な例外処理
try:
    num = int(input( "整数を入力してください:"))
    result = 100 / num
    print(result)
ただしZeroDivisionError:  #例外タイプ
    print( "分母を0"にすることはできません)
ただしValueError:
    print( "不正なタイプ")
結果としての例外を除く:   #不明な例外
    print( "不明なエラー%s"%結果)
else:
    print( "例外が見つからない場合、この部分のコードが実行されます")
finally:
    print( "finally:whatever例外が見つかった場合、その部分のコードが実行されます ")

 

#積極的に例外をスローします
def input_password():
    password = input( "input password:")

    if 8 <= len(password)<= 16:
        return password
    elif len(password)<8:
        exception = Exception( "パスワードが長すぎますShort ")
        raise exception
    elif len(password)> 16:
        exception = Exception(" Password length is too long ")
        raise exception


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

おすすめ

転載: blog.csdn.net/Michael_234198652/article/details/109157617