Python 异常处理
本文最后更新于 226 天前,其中的信息可能已经有所发展或是发生改变。

递归调用形式

def get_price():    #递归调用形式
    try:
        price = float(input("Enter price: "))
        return price
    except ValueError:
        print("Please enter a valid price")
        return get_price()

循环形式

def get_quantity():     #循环形式
    while True:
        try:
            quantity = int(input("Enter quantity: "))
            return quantity
        except ValueError:
            print("Please enter a valid quantity")

多种异常处理

fileName = "inventory.txt"
def read_file(fileName):        #多种异常处理
    try:
        with open(fileName, "r") as f:
            inventory = f.read()
            return inventory
    except FileNotFoundError:
        print("File not found")
        return read_file(fileName)
    except PermissionError:
        print("Permission denied")
        return read_file(fileName)

异常处理除法实例

def chufa():        #异常处理除法实例
    try:
        x = int(input("Enter the item number: "))
        y = int(input("Enter the quantity: "))
        z = x/y
        print(f"{x}/{y}={z}")
    except ZeroDivisionError:
        print("Quantity can't be zero")
        chufa()
    except ValueError:
        print("Please enter a valid number")
        chufa()

获取异常对象以及finally操作

def read_csv(fileName):  #获取异常对象以及finally操作
    try:
        file = open(fileName, "r")
        for f in file:
            csv = f.read()
            return csv
    except PermissionError:
        print("Permission denied")
        return read_file(fileName)
    except FileNotFoundError as e:
        print(type(e),e)
        return read_file(fileName)
    finally:#finally要放在最后
        file.close()

类中抛出异常

y = 0
if y == 0:
    raise ZeroDivisionError("不能为0")#raise出的应该是一个异常对象

自定义异常类

class aNewCustomException(Exception):#异常类必须继承Exception类
    pass

向上继续抛出异常

def chufa():        
    try:
        x = int(input("Enter the item number: "))
        y = int(input("Enter the quantity: "))
        z = x/y
        print(f"{x}/{y}={z}")
    except ZeroDivisionError as e:
        print("Quantity can't be zero")
        raise e#向上抛出
    except ValueError:
        print("Please enter a valid number")
        raise e

多个异常

def chufa():        
    try:
        x = int(input("Enter the item number: "))
        y = int(input("Enter the quantity: "))
        z = x/y
        print(f"{x}/{y}={z}")
    except (ZeroDivisionError,ValueError) as e:
        print("代码出现了问题")

一网打尽所有的异常

def chufa():
    try:
        x = int(input("Enter the item number: "))
        y = int(input("Enter the quantity: "))
        z = x/y
        print(f"{x}/{y}={z}")
    except:
        print("代码出现了问题")

else用法

def chufa():
    try:
        x = int(input("Enter the item number: "))
        y = int(input("Enter the quantity: "))
        z = x/y
    except:
        print("代码出现了问题")
    else:
        print(f"{x}/{y}={z}")#没有出现异常

兜底匹配所有的异常

def chufa():
    try:
        x = int(input("Enter the item number: "))
        y = int(input("Enter the quantity: "))
        z = x/y
        print(f"{x}/{y}={z}")
    except ZeroDivisionError as e:
        print("Quantity can't be zero")
        raise e#向上抛出
    except ValueError:
        print("Please enter a valid number")
        raise e
    except Exception:#兜底匹配,Exception可以被所有类型的异常匹配成功
        print("有异常,但不是ZeroDivisionError和ValueError")
        raise e

finally和else

def get_quantity():
    '''
    finally和else
    finally无论是否有异常都会执行出来
    else只有完全没有异常才会执行出来
    若完全无异常,先执行finally后执行else
    else要在finally之前
    finally要放在最后
    '''
    try:
        quantity = int(input("Enter quantity: "))
        print(quantity)
    except:
        print("有异常")
    else:#else要在finally之前
        print("成功执行完毕")
    finally:#finally要放在最后
        print("不管有没有异常,都会执行")
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇