引言:在程序运行过程中影响程序正常运行的内容, 称为异常
一.异常的分类
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
BaseException类是所有的异常类的基类。如果骂我们想要捕捉所有的系统自定义的异常类型,我们就可以使用 except BaseException:语句去实现。
二.try
…except
…else
…finally
语句(捕获异常)
# 捕获异常
try:
f = open("yoooo.txt", 'w')
f.write("这是一个测试文件")
# 注意: except语句不一定会执行, 只有在try语句中出现IOError报错时, 才会执行.
except IOError as e:
print(e)
# print("没有找到文件或者文件读取失败")
# 如果没有捕获到异常, 则执行else语句的内容
else:
print("文件内容写入成功")
# 无论是否捕获到异常, 都执行的语句.
finally:
f.close()
print("文件已经关闭")
不指定异常类型的except
的使用
try:
f = open('hello.txt')
# f.write("这是一个测试文件")
f.read()
# 不建议捕获所有的异常, 因能不能定位错误的位置.
except:
print("捕获所有的异常....")
else:
print("如果没有捕获到异常, 执行else语句")
finally:
f.close()
print("有异常或者没有异常都会执行")
捕获多个异常
try:
d = dict(a=1, b=2)
print(d['f']) # KeyError
print(a) # NameError
except (KeyError, NameError) as e:
print(e)
else:
print("没有产生异常")
finally:
print("无论是否产生异常的清理操作")
print("new start")
三.抛出异常
class AgeError(BaseException):
pass
def get_age(age):
if 0 < age <= 200:
print(age)
else:
# 如果raise抛出异常, 程序后面的代码不会再执行.
raise AgeError('invaild age')
print("121234124312")
get_age(300)
get_age(50)
四.断言
def is_huiwen_num(num):
snum = str(num)
return snum == snum[::-1]
# 如果希望程序中的所有assert语句不执行, 那么给python -O 脚本名
if __name__ == "__main__":
assert is_huiwen_num(101) == True
assert is_huiwen_num(100) == True, "error"
print("yooooo!")