try:
num = int(input('请输入数字:'))
print(num)
print('Hello World')
except ValueError:
print('您输入含有不是数字的字符了')
print('到这里了')
try:
num = int(input('请输入数字:'))
print(num)
dic = {'name': 'albert'}
print(dic['age'])
print('Hello World')
lst = [i for i in range(10)]
print(lst[101])
print(777)
except ValueError:
print('您输入含有不是数字的字符了')
except KeyError:
print('此键不存在!!')
except IndexError:
print('超出列表下标!!')
print('到这里了-2')
try:
dic = {'name': 'albert'}
print(dic['age'])
print('Hello World')
lst = [i for i in range(10)]
print(lst[101])
print(777)
except Exception:
print('出现错我啦')
try:
lst = [i for i in range(10)]
print(lst[101])
dic = {'name': 'albert'}
print(dic['age'])
print('Hello World')
print(777)
except Exception as e:
print(e)
"""
什么时候用万能? 什么时候用多分支?
如果你对错误信息不关心,只是想要排除错误让程序继续运行>>>用万能异常.
你对错误信息要进行明确的分流,让你的程序多元化开发>>>用分支异常
"""
def func():
pass
def func1():
pass
dic = {
1: func,
2: func1}
try:
num = int(input('请输入序号'))
dic[num]()
except ValueError:
print('请输入数字')
except KeyError:
print('请输入范围内的序号')
except Exception:
print('程序出现意料之外的错误....')
"""
except 必须依赖于try, else必须依赖于except和try
finally只是依赖于try.
"""
try:
dic = {'name': 'albert'}
print(dic['age'])
l1 = [1, 2]
print(l1[100])
print(111)
except KeyError:
print('没有此键')
except IndexError:
print('没有此下标')
else:
print('没出现错误啊,good')
finally:
print('finally 666')
"""
1、finally 用在 关闭数据库连接,文件句柄关闭,数据保存等
2、在return结束函数之前,执行finally代码.
"""
try:
dic = {'name': '嘉欣'}
print(dic['age'])
l1 = [1, 2]
print(l1[100])
finally:
print('finally 777')
def func():
try:
print(111)
return 666
finally:
print(222)
print(func())
raise ValueError('出现了value错误')
assert 1 == 2
print(111)
class MyError(BaseException):
def __init__(self,msg):
self.msg=msg
def __str__(self):
return self.msg
try:
raise MyError('类型错误')
except MyError as e:
print(e)
|