常见的异常
在程序运行过程中影响程序正常运行的内容, 称为异常.
NameError
print(a)
IndexError: 索引错误
li = [1,2,3,4]
print(li[8])
KeyError
d = dict(a=1, b=2)
print(d['f'])
ZeroDivisionError: 除0错误
print(10/(2-2))
AttributeError: 对象没有该属性
class Student(object):
def __init__(self, name, age):
self.name = name
self.age = age
def echo(self):
print(self.name, self.age)
s1 = Student("cooffee", 10)
print(s1.scores)
FileNotFoundError
with open('/tmp/passwd9') as f:
print(f.read(5))
_ try _except语句
try:
f = open("hello.txt", 'r')
f.write("这是一个测试文件")
except IOError as e:
print('异常:',e)
else:
print("文件内容写入成功")
finally:
f.close()
print("文件已经关闭")

不指定异常类型的except使用
try:
f = open('hello.txt')
f.write('cooffee')
except:
print("捕获所有的异常....")
else:
print("如果没有捕获到异常, 执行else语句")
finally:
f.close()
print("有异常或者没有异常都会执行")

捕获多个异常
try:
d = dict(a=1, b=2)
print(d['f'])
print(a)
except (KeyError, NameError) as e:
print(e)
else:
print("没有产生异常")
finally:
print("无论是否产生异常的操作")
print("new start")

抛出异常
raise: 关键字, 用来抛出异常.
raise 抛出异常的名称, 抛出异常的详细显示
自定义异常类
所有的异常实际上是一个类, 所以异常的父类都是BaseException.
class AgeError(BaseException):
pass
def get_age(age):
if 0 < age <= 200:
print(age)
else:
raise AgeError('invaild age')
get_age(1000)
get_age(100)

抛出异常与继承
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
for cls in [B, C, D]:
try:
raise cls()
except D:
print("D")
except C:
print("C")
except B:
print("B")

断言assert
assert 语句 如果这个语句为真则通过,为假则报错
def is_huiwen_num(num):
snum = str(num)
return snum == snum[::-1]
if __name__ == "__main__":
assert is_huiwen_num(100) == True, "error"
assert is_huiwen_num(101) == True
print("assert")

_logging模块
配置日志的信息:
1). 日志级别: debug, info, warning, error, critical
2). level: 指日志级别为info及以上的日志信息会被记录到文件中;
3). format: 指定日志的格式, 可以去logging.Formatter查看参考信息
import logging
s = '0'
n = int(s)
# 配置日志的信息:
# 1). 日志级别: debug, info, warning, error, critical
# 2). level: 指日志级别为info及以上的日志信息会被记录到文件中;
# 3). format: 指定日志的格式, 可以去logging.Formatter查看参考信息
logging.basicConfig(filename="hello.log",level=logging.INFO,
format="%(asctime)s - %(filename)s[%(lineno)d] - %(levelname)s: %(message)s")
logging.debug("this is a debug info")
logging.info("this is a info")
logging.warning("这是一条警告信息")

异常案例
判断输入的是否是数字,如果不是则异常报错
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again")

|