try:
#print('代码块,或者你要写的逻辑')
# int('wewe')
list1 = [1,2,4,5,6]
# list1[666]
except ValueError as e:
print('ValueError',e)
except IndexError as e :
print('IndexError',e)
except Exception as e:#放在最后,包含所有的错误
print('如果上个代码块执行出错,执行此代码块')
else:
print('最开始代码块有错就不执行else,没错就执行else')
finally:
print('代码不管出错不出错都会执行该代码!')
print('*'*12+'主动触发异常'+'*'*12)
try:
#int('eeee')
print('hhhh')
raise Exception('主动跳出异常')#放在try代码块中
except Exception as e :
print(e)
print('例子应用场景')
def db():
'''数据库函数'''
return False
def index():
try:
result = db()
# int('eee')
if result == False:#数据库执行出现问题
raise Exception('数据库执行出现问题')
except Exception as e:
str_error = str(e)
print(str_error)
r = open('error.txt','a',encoding = 'utf-8')
r.write(str_error)
r.write('
')
index()
print('*'*12+'自定义异常方法'+'*'*12)
class OldBoy(Exception):
def __init__(self,msg):
self.message = msg
def __str__(self):
return self.message
try:
raise OldBoy('我错了.....')
except Exception as e:#e---->oldboy
print(e)