Python的异常及处理

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...')

测试结果如下图所示:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值