try:print(name)except(NameError, ZeroDivisionError)as rst:print(rst)# 输出结果
name 'name'isnot defined
捕获所有异常
Exception是所有程序异常类的父类。
try:print(name)except Exception as rst:print(rst)# 输出结果
name 'name'isnot defined
3. 异常的else:如果没有异常要执行的代码
try:print(1)except Exception as rst:print(rst)else:print("正常终了")# 输出结果1
正常终了
4. 异常的finally:无论是否异常都要执行的代码,例如关闭文件。
try:print(1)except Exception as rst:print(rst)else:print("else执行")finally:print("finally执行")# 输出结果1else执行
finally执行
5. 命令行执行python文件
python3 *.py
6. 异常的传递
# 从外层的try传递到内层的trytry:print(1)try:print(name)except Exception as rst:print(rst)except:print("异常终了")# 输出结果1
name 'name'isnot defined
7. 自定义异常
抛出自定义异常的语法
raise 异常类对象
示例
classPwdInputError(Exception):def__init__(self):
self.err ="密码不正确!"def__str__(self):return self.err
defmain():try:
con =input("Please input your password: ")if con !="123456":raise PwdInputError()except Exception as rst:print(rst)
main()# 输出结果
Please input your password:124
密码不正确!