def password_verify(pwd):
"""密碼大於8位返回值,小於八位主動丟擲異常
"""if len(pwd) >= 8:
return pwd
elif len(pwd) < 8:
# 自定義異常,並丟擲
pwd_error = exception('密碼長度小於8位')
raise pwd_error
# 呼叫
pwd_a = input('請輸入密碼:')
try:
password = password_verify(pwd_a)
# 當有異常時,列印密碼語句將不會執行
print(password)
except exception as e:
print('異常為:{}'.format(e))
結果:請輸入密碼:1
異常為:密碼長度小於8位
請輸入密碼:12345678
使用者輸入的密碼為:12345678
python自定義異常和主動丟擲異常
python自定義異常和主動丟擲異常 自定義異常主要是利用了自己定義的異常類的名字,對異常進行分門別類,再沒有別的作用 import re import os class existserror exception pass class keyinvaliderror exception pass ...
丟擲異常 自定義異常
1 try catch try catch是這之間所包含的 如果出現異常時捕獲他,並進行處理的,如果 之間有錯誤,不會影響程式繼續執行下去,程式會繼續往後執行。2 throw 是在程式中明確丟擲引發的異常,比如throw new exception 3 finally 不管有沒有異常程式段中都會被執...
如何丟擲異常,自定義異常
定義乙個方法,丟擲 陣列越界和算術異常 多個異常 用 隔開 public void test1 int x throws arrayindexoutofbound ception,arithmeticexception 資料越界異常 else if x 1 算術異常 else if x 2 publ...