python的異常丟擲

2022-08-09 18:00:24 字數 1022 閱讀 1312

例子:
編寫乙個不能處0的案例

s1=int(input("請輸入乙個數字:"))

try:

result = 9 / s1

except:

print("不能為0")

結果:
請輸入乙個數字:0

不能為0

process finished with exit code 0

例子:

try:

s1 = int(input("請輸入乙個數字:"))

result = 9 / s1

except zerodivisionerror:

print("不能為0")

except exception as a:

print(f"錯誤提示")

else:

print("123")

finally:

print("有沒有都會執行")

結果:

請輸入乙個數字:0

不能為0

有沒有都會執行

process finished with exit code 0

例子:

輸入的年齡大於0且小於100

def getage():

age = int(input("請輸入年齡:"))

if age>0 & age<100:

return age;

ex=exception("age輸入錯誤")

return ex;

print(getage())

結果:

請輸入年齡:-1

age輸入錯誤

process finished with exit code 0

python 丟擲 python丟擲異常的方法

python丟擲異常的方法 閱讀 89 異常是python物件,表示乙個錯誤。當python指令碼發生異常時我們需要捕獲處理它,否則程式會終止執行。常見異常 attributeerror 呼叫不存在的方法引發的異常 eoferror 遇到檔案末尾引發的異常 importerror 匯入模組出錯引發的...

python 丟擲異常 python 異常

異常的概念 捕獲異常 異常的傳遞 丟擲異常 程式在執行時,如果 python 直譯器 遇到 到乙個錯誤,會停止程式的執行,並且提示一些錯誤資訊,這就是 異常 程式停止執行並且提示錯誤資訊 這個動作,我們通常稱之為 丟擲 raise 異常 程式開發時,很難將 所有的特殊情況 都處理的面面俱到,通過 異...

python丟擲異常

1 python 使用 raise 語句丟擲乙個指定的異常。raise nameerror hithere traceback most recent call last file line 1,in module raise nameerror hithere nameerror hithere ...