python的異常拋出

一、異常拋出概念

  • 異常:程序運行時,若是python解釋器遇到一些錯誤,而且提示一些錯誤信息及其說明
  • 拋出:程序異常而且提示等動做

二、捕獲異常

2.一、最簡單的捕獲異常方式

  • 在程序中捕獲異常通常用try來捕獲python

  • 最簡單捕獲方式code

    try:
        異常語法
    except:
        異常輸出

例子:

編寫一個不能處0的案例開發

s1=int(input("請輸入一個數字:"))
try:
    result = 9 / s1
except:
    print("不能爲0")

結果:

請輸入一個數字:0
不能爲0

Process finished with exit code 0

2.二、根據類型捕獲異常

  • 在程序中咱們要根據不一樣的錯誤返回不一樣的信息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

2.三、捕獲未知異常

  • 在程序中會遇到未知錯誤,又想讓程序運行,因此咱們要捕獲斌輸出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

2.四、異常拋出的完整語法

  • 實際開發中有些難度,下面爲完整的格式

    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

2.五、主動建立異常拋出

  • 咱們會在程序中設置一些爲知足條件就出現異常,終止程序

例子:

輸入的年齡大於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
相關文章
相關標籤/搜索