当前位置:   article > 正文

【Python入门教程】第54篇 异常处理之try…except…else_python try except else

python try except else

本篇我们学习异常处理中的另一种语法形式:try…except…else 语句。

try…except…else 语句简介

try 语句还支持一个可选的 else 分支,语法如下:

try:
    # 业务代码
except:
    # 异常处理
else:
    # 没有异常时执行的代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

try…except…else 语句的执行过程如下:

  • 如果 try 分支中产生了异常,跳过该分支中的其他语句并执行 except 分支。
  • 如果 try 分支中没有异常产生,执行 else 分支中的语句。

try…except…else 语句示例

接下来我们看几个 try…except…else 语句的示例。

使用 try…except…else 语句控制流程

以下示例演示了如何使用 try…except…else clause 开发一个计算体重指数(BMI)的程序:

首先,创建一个基于身高和体重计算 BMI的函数:

def calculate_bmi(height, weight):
    """ calculate body mass index (BMI) """
    return weight / height**2
  • 1
  • 2
  • 3

然后,定义一个评价 BMI 的函数:

def evaluate_bmi(bmi):
    """ evaluate the bmi """
    if 18.5 <= bmi <= 24.9:
        return 'healthy'

    if bmi >= 25:
        return 'overweight'

    return 'underweight'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

最后,定义一个 main() 函数,提示用户输入身高和体重,打印最终的 BMI:

def main():
    try:
        height = float(input('Enter your height (meters):'))
        weight = float(input('Enter your weight (kilograms):'))

    except ValueError as error:
        print('Error! please enter a valid number.')
    else:
        bmi = round(calculate_bmi(height, weight), 1)
        evaluation = evaluate_bmi(bmi)

        print(f'Your body mass index is {bmi}')
        print(f'This is considered {evaluation}!')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

main() 函数使用 try…except…else 语句控制流程,如果输入的身高或体重不是数字,将会产生 ValueError 异常。如果没有产生异常,将会执行 else 分支,计算 BMI 指数并评级该结果。

以下是完整的代码:

def calculate_bmi(height, weight):
    """ calculate body mass index (BMI) """
    return weight / height**2


def evaluate_bmi(bmi):
    """ evaluate the bmi """
    if 18.5 <= bmi <= 24.9:
        return 'healthy'

    if bmi >= 25:
        return 'overweight'

    return 'underweight'


def main():
    try:
        height = float(input('Enter your height (meters):'))
        weight = float(input('Enter your weight (kilograms):'))

    except ValueError as error:
        print(error)
    else:
        bmi = round(calculate_bmi(height, weight), 1)
        evaluation = evaluate_bmi(bmi)

        print(f'Your body mass index is {bmi}')
        print(f'This is considered {evaluation}!')

main()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

try…except…else…finally 语句

以下示例使用了完整的 try…except…else…finally 语句:

fruits = {
    'apple': 10,
    'orange': 20,
    'banana': 30
}

key = None
while True:
    try:
        key = input('Enter a key to lookup:')
        fruit = fruits[key.lower()]
    except KeyError:
        print(f'Error! {key} does not exist.')
    except KeyboardInterrupt:
        break
    else:
        print(fruit)
    finally:
        print('Press Ctrl-C to exit.')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

代码执行过程如下:

  • 首先,定义一个字典 fruits,包含了三个元素。
  • 其次,使用 while 循环重复获取用户输入。当用户输入 Ctrl-C 时退出循环
  • 最后,在 while 循环内部使用 try…except…else…finally 语句,在字典中查找用户输入的元素。

如果用户输入的 key 不存在,抛出 KeyError 异常,执行 except 分支。如果用户输入 Ctrl-C,抛出 KeyboardInterrupt 异常,执行 break 语句终止循环。如果在字典 fruits 中找到了输入的 key,打印相应的元素。最后,finally 语句总是会被执行,提示用户输入 Ctrl-C 退出程序。

以上语法形式中,else 分支在 try 分支之后,finally 分支之前执行。

总结

  • try…except…else 语句提供了一种控制程序流程的方法。
  • 如果 try 分支中没有产生任何异常,执行 else 分支。
  • else 分支在 try 分支之后,finally 分支之前执行。
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号