Python教程

python学习笔记(8)异常处理

本文主要是介绍python学习笔记(8)异常处理,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
try:
    pass  # 正常执行代码
except Exception as e:
    pass  # 报错信息和异常处理机制

try:
    with open("vue3.html") as f:
        data = f.read()
    print("正常打开")
except Exception as e:  # Exception是所有异常
    print("e",e)

# try:
#     with open("vue3.html") as f:
#         data = f.read()
#     print("正常打开")
#     d = {}
#     d["a"]
# except (FileNotFoundError, KeyError) as e:  # 文件没有找到异常
#     print("e",e)

try:
    with open("vue3.html") as f:
        data = f.read()
    print("正常打开")
    d = {}
    d["a"]
except FileNotFoundError as e:  # 文件没有找到异常
    print("e",e)

except KeyError as e:  # key错误异常
    print("e",e)

finally:
    print("无论是否出现异常,一定会执行!")

# 自己定义异常
class TooLongException(Exception):
    def __init__(self, *args: object) -> None:
        self.len = len
    
    def __str__(self):
        return "输入姓名长度是" + str(self.len) + ",超过长度了"

try:
    name = input("enter your name:")
    if len(name) > 5:
        raise TooLongException(len(name))
    else:
        print(name)

except TooLongException as error:
    print("打印异常信息:", error)

 

这篇关于python学习笔记(8)异常处理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!