【Python】异常处理

本文介绍了Python中异常处理的基础知识,展示了如何使用try-except语句来捕获并处理异常。通过示例,解释了不加异常处理时程序会因OSError而中断,而添加异常处理后能够优雅地捕获错误并打印相关信息,确保程序的正常执行。此外,还讨论了异常处理在程序流程控制中的重要性。
摘要由CSDN通过智能技术生成

如果不加异常处理

def test(input):
    # try:
    print("1: {}".format(input))
    raise OSError
    print("2222") # 是不会执行到的
    #
    # except Exception as err:
    #     print(err)

if __name__ == '__main__':
    input = "hello"
    test(input)
    print("fixed error")

报错信息

1: hello
Traceback (most recent call last):
  File "/Users/.../异常处理.py", line 13, in <module>
    test(input)
  File "/Users/.../异常处理.py", line 5, in test
    raise OSError
OSError

加了异常处理以后

def test(input):
    try:
        print("1: {}".format(input))
        raise OSError
        print("2222") ## 不会运行到的

    except Exception as err:
        print("get err:{}".format(err))

if __name__ == '__main__':
    input = "hello"
    test(input) # 忽略这个函数内部的异常
    print("fixed error") # 可以处理之后的打印信息

正常打印信息

1: hello
get err:

fixed error

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值