python学习day-03(异常捕获)

异常处理的必要性

        异常处理是确保程序健壮性的重要手段,能够有效应对运行时可能出现的意外情况,如网络请求失败、用户输入不合法或文件操作错误等。

基础语法结构

Python的异常处理使用try-except语句,基础结构如下:

try:
    # 可能引发异常的代码块
except ExceptionType1:
    # 处理特定异常类型的代码
except ExceptionType2:
    # 处理另一种异常的代码

多异常捕获示例

能针对不同异常类型编写不同的处理逻辑:

try:
    result = 10 / 0
    value = int("abc")
except ZeroDivisionError:
    print("发生了除零错误")
except ValueError:
    print("数值转换失败")

异常对象获取

通过as关键字可以获取异常对象实例:

try:
    file = open("nonexistent.txt")
except IOError as e:
    print(f"文件操作错误:{e.strerror}")

通用异常捕获

使用基础异常类可以捕获所有异常:

try:
    risky_operation()
except Exception as e:
    print(f"发生未知错误:{repr(e)}")

主动抛出异常

在检测到逻辑错误时,可手动触发异常:

def calculate_discount(price, discount):
    if discount > 1.0:
        raise ValueError("折扣率不能超过100%")
    return price * discount
 

你可能感兴趣的:(python,学习,开发语言)