python标准异常:
- BaseException:所有异常的父类
- SystemExit:解释器请求退出
- KeyboardInterrupt:用户中断执行(通常ctrl+c)
- Exception:常规错误父类
- NameError: name ‘a’ is not defined
- TyepError: Can’t convet ‘int’ object to str implictly
- IndexError: list index out of range
- SyntaxError: unexpected EOF while parsing
- IndentationError: unexpected indent
- FileNotFoundError:[Errno 2] No sunch file or directory: ‘a.txt’
- ImportError: No module named ‘mathss’
- AttributeError:‘str’ object has no attribute’abc’
def dealwith_file():
try:
f = open('file',encoding='utf-8')
for line in f:
int(line)
return True
except Exception as e:
print(e)
return False
finally:
'''不管try语句中的代码是否报错,都会执行finally分支中的代码'''
'''去完成一些连接操作的收尾工作'''
print('finally 被执行了')
f.close()
ret = dealwith_file()
print(ret)
断言:
assert语句用于检测某个条件表达式是否为真。assert语句又称为断言语句,assert认为检测的表达式永远为真,if语句中的条件判断都可以使用assert语句检测。
assert “mode” in [ “train”,“eval”,“inderence”]
注意:如果"mode"不在其中,则触发异常。
#断言:在特定情况下触发执行某个错误
name='xl'
assert name == 'xl',NameError("用户名不正确")
age=20
class AgeError(Exception):
"""docsrting for ClassName"""
pass
age=17
if age <18:
raise AgeError("您的年龄太小了,不能进入娱乐场所")