1

次のコードを検討してください。

class Test(object):
    def __enter__(self):
        pass
    def __exit__(self,type,value,trace):
        if type:
            print "Error occured: " + str(value.args)
            #if I changed the next line to 'return True', the
            #'print "should not happen"' statements are executed, but the
            #error information would be only printed once (what I want)
            return False
        return True

with Test():
    with Test():
        with Test():
            raise Exception('Foo','Bar')
        print "should not happen"
    print "should not happen"

例の出力:

エラーが発生しました: ('Foo', 'Bar')

エラーが発生しました: ('Foo', 'Bar')

エラーが発生しました: ('Foo', 'Bar')

ネストされたステートメントがいくつwithかあり、コードのどこかで例外が発生した場合を処理したいと考えています。私が達成したいのは、実行が停止されることです(上記の例では「発生しないはずです」という出力はありません)が、エラー情報は一度だけ出力されます。したがって、同じエラーが既に処理されているかどうかを何らかの形で知る必要があります。

これをどのように達成できるか考えていますか?

4

2 に答える 2

1

error_handled例外に属性を追加してテストできます。

class Test(object):
    def __enter__(self):
        pass
    def __exit__(self,type,value,trace):
        if type:
            if not getattr(value,'error_handled', False):
                value.error_handled = True
                print "Error occured: " + str(value.args)

with Test():
    with Test():
        with Test():
            raise Exception('Foo','Bar')
        print "should not happen"
    print "should not happen"
于 2014-07-07T16:54:18.673 に答える