Python Exception的一个妙用

来源:互联网 发布:wlan直连软件 编辑:程序博客网 时间:2024/06/07 01:07

在程序运行过程中,我们往往会遇到一些Exception,但Python的Exception不仅能针对异常,同时也能处理一些非异常的情况。

比如:

class Found(Exception): passdef searcher():    if ...success...:        raise Found()    else:        returntry:    searcher()except Found:                    # Exception if item was found    ...success...else:                            # else returned: not found    ...failure...

在这个例子中,Exception被用来处理Success的情况,实属程序中的奇葩,如果修改为如下程序,则会好很多:

class Failure(Exception): passdef searcher():    if ...success...:        return ...founditem...    else:        raise Failure()try:    item = searcher()except Failure:    ...report...else:    ...use item here...

和之前的例子非常类似,只是这里用来处理失败的情况,当然会自然一些。





0 0