Day_14_AM_Exception
# 错误; error,
# 异常: Exception
# 1a = 10 # SyntaxError: invalid syntax, 错误的语法(代码不规范)
# print(a) # NameError: name 'a' is not defined, 变量未定义
# [][0] # IndexError: list index out of range, 下标越界
# 1 + '1' # TypeError: unsupported operand type(s) for +: 'int' and 'str', 类型错误
# 1/0 # ZeroDivisionError: division by zero, 运算错误
# 异常处理/: 异常捕获
# 作用: 防止代码报错, 导致后面的程序无法执行
try:
a = 10 / 0
print(a)
except:
print('报错了')
# try:
# a = a + 1
# except ZeroDivisionError as e:
# print('除0错误了', e)
# except NameError as e:
# print('未定义错误了', e)
try:
a = 1/0
except Exception as e:
print('出错了', e)
# try-except-else
try:
a = 1/1
print('a =', a)
except Exception as e:
print('出错了', e)
else:
print('未出错')
# try-except-finally
try:
a = 1/0
print('a =', a)
except Exception as e:
print('出错了', e)
finally:
print('不管有没有错, 我都会最后执行')
# # 抛出异常; 让程序报错
# raise NameError('哈哈,这是我抛出的错误!')
# 自定义异常
class MyException(Exception):
def __init__(self, code):
self.code = code
try:
raise Exception('10001')
except Exception as e:
print(e)
print(type(e))
# 断言assert:预测
def f(n):
assert n!=0, 'n不能为0'
# 预测n!=0:
# 如果成立正常执行
# 不成立抛出异常
a=1/n
print(a)
f(0)