- 異常:程序運行時,若是
python解釋器
遇到一些錯誤,而且提示一些錯誤信息及其說明- 拋出:程序異常而且提示等動做
在程序中捕獲異常通常用try
來捕獲python
最簡單捕獲方式code
try: 異常語法 except: 異常輸出
編寫一個不能處0的案例開發
s1=int(input("請輸入一個數字:")) try: result = 9 / s1 except: print("不能爲0")
請輸入一個數字:0 不能爲0 Process finished with exit code 0
在程序中咱們要根據不一樣的錯誤返回不一樣的信息get
代碼格式以下:input
try: 異常代碼 except 異常類型: 提示 except 異常類型: 提示
try: s1 = int(input("請輸入一個數字:")) result = 9 / s1 except ZeroDivisionError: print("不能爲0") except ValueError: print("請輸入正確的整數")
結果1:it
請輸入一個數字:a 請輸入正確的整數 Process finished with exit code 0
結果2:io
請輸入一個數字:0 不能爲0 Process finished with exit code0
在程序中會遇到未知錯誤,又想讓程序運行,因此咱們要捕獲斌輸出class
格式:語法
try: 異常代碼 except ZeroDivisionError: 錯誤提示 except Exception as a: 未知信息
例子:程序
try: s1 = int(input("請輸入一個數字:")) result = 9 / s1 except ZeroDivisionError: print("不能爲0") except Exception as a: print(f"錯誤提示{a}")
結果:
請輸入一個數字:a 錯誤提示invalid literal for int() with base 10: 'a' Process finished with exit code 0
實際開發中有些難度,下面爲完整的格式
try: 異常代碼 except 異常類型: 提示信息 except Exception as a: 提示信息 else: 沒有異常代碼 finally: 有沒有異常都會執行
例子:
try: s1 = int(input("請輸入一個數字:")) result = 9 / s1 except ZeroDivisionError: print("不能爲0") except Exception as a: print(f"錯誤提示{a}") 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