python异常
案例一
自定义异常
class ShortInputException( Exception ): #继承自Exception
#定义构造方法
#__init__是构造方法,用于类的对象初始化
# self相当于Java中的this,表示对象的地址
def __init__(self,value):
self.value=value
def __str__(self):
print("调用了__str__方法...")
return repr(self.value) #repr()Python的内置函数
try:
raise ShortInputException("这是一个异常...") #抛出异常
except ShortInputException as e:
print(e)
测试结果如下图所示:
案例二
为了让错误的信息更丰富,将一个异常与一个编号绑定,将来可以通过一个编号来解决异常
class ShortInputException( Exception ): #继承自Exception
#定义构造方法
def __init__(self,value):
self.value=value
def __str__(self):
print("调用了__str__方法...")
return repr(self.value) #repr()Python的内置函数
try:
s=input('请输入一个人名:\n')
if len(s)<2:
raise ShortInputException('人名长度必须大于2位...')
except ShortInputException as e:
print(e)
测试结果如下图所示:
案例三
a_list=['china','america','england','France']
while True:
print('请输入国家索引\n')
try:
n=int(input()) #1.不存在 2.非数字
print(a_list[n])
except IndexError:
print('没有这个元素...')
except ValueError:
print('不是一个有效的数字...')
else:
break
print('程序结束...')
测试结果如下图所示:
*案例四
当try内的代码运行报错的时候输出except内的信息,不过无论如何,finally中的内容一定会被执行的
try:
4/0
except:
print(3)
finally:
print(5)
测试结果如下图所示:
案例五
with 容器类的方法:定义一个类,只要这个类中实现 enter() exit()
import time
class Timer(object):
def __enter__(self):
print('正在执行__enter__方法...')
self.start=time.time()
def __exit__(self,exception_type,exception_val ,trace):
self.end=time.time()
print('程序运行的时间为:'+str(self.end-self.start))
print(exception_type)
print(exception_val)
print(trace)
with Timer() as t:
for i in range(100):
print('hello,world...')
测试结果如下图所示: