首页 > 其他 > 详细

try....exception....finally

时间:2017-11-13 22:21:18      阅读:252      评论:0      收藏:0      [点我收藏+]
class MyException(Exception):
    def __init__(self,msg):
        self.msg=msg
    def __str__(self):
        return self.msg


try:
    print(‘start‘)
    raise MyException(‘this is a custom exception‘)##手动触发会被Exception捕获
except Exception as e:
    print(e)
finally:
    print(‘end‘)

##ret
start
 
this is a custom exception
 
end
import time
try:
    print(start...)
    time.sleep(10)
except KeyboardInterrupt as e:##按ctrl+c会执行这个语句块
    print(you press ctrl+c)
finally:
    print(end...)


myexception=MyException(‘231‘)
print(hasattr(myexception,‘msg‘))#True
print(hasattr(myexception,‘msg1‘))#False
print(getattr(myexception,‘__str__‘)())#231
setattr(myexception,‘fun‘,lambda x:x)
print(getattr(myexception,‘fun‘)(1234))#1234
delattr(myexception,‘fun‘)

 

  

try....exception....finally

原文:http://www.cnblogs.com/howhy/p/7828340.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!