2017-11-20 12 views
0

これはちょっと難しいかもしれないが、なんとか実現可能だと思うが、私は助けが必要だ。 main()関数内から2つの関数を実行したいと思います。 私は2つの例外を別々にキャッチすることができるようにしたいと思いますが、まだ両方を実行して、もう一方が例外を発生させた場合は、少なくとも1つの結果を取得できます。python - 例外の後に移動し、後でそれを上げる

のは、私が持っているとしましょう:

def foo(): 
    raise TypeError 

def bar(): 
    return 'bar' 

私は(hereから適応)ない場合:

def multiple_exceptions(flist): 
    for f in flist: 
     try: 
      return f() 
     except: 
      continue 

def main(): 
    multiple_exceptions([foo, bar]) 

main() 

main()'bar'を返すだろうが、私はまだ例外をスローできるようにしたいのですが結局のところfoo()からです。このようにして、私はまだ私の機能の1つの結果を得て、そのエラーに関する情報は他の機能にも発生しました。

+0

mainからこれらのメソッドを呼び出す方法は? –

+0

これを解読するコードを編集しました。 – umbe1987

+0

あなたは現在どのような出力を得ていますか? –

答えて

0

感謝を。

def multiple_exceptions(flist): 

    exceptions = [] 

    for f in flist: 
     try: 
      f() 
     except Exception as e: 
      exceptions.append(e.message) 
      continue 

    return exceptions 

def main(): 
    multiple_exceptions([foo, bar]) 

error_messages = main() # list of e.messages occurred (to be raised whenever I want) 

その後、私は例えば、私のような例外を発生させることができます:私はこれを行うことによって解決 raise Exception(error_messages[0])(この場合、私は最初のことしか気にしません)。

+0

あなたがこの質問に最もよく答えると感じたら、それを答えとして受け入れる。ソリューションを書いたからといって質問を開いたままにする必要はありません。正しい場合は自分の答えを受け入れることに間違いはありません。 – Bilkokuya

1

あなたは、例えば「と」を使用して例外を捕捉し、保存することができます。:コメントの

try: 
    raise Exception('I am an error!') 
    print('The poster messed up error-handling code here.') #should not be displayed 
except Exception as Somename: 
    print(Somename.message) 
    # you'll see the error message displayed as a normal print result; 
    # you could do print(stuff, file=sys.stderr) to print it like an error without aborting 

print('Code here still works, the function did not abort despite the error above') 

...or you can do: 
except Exception as Somename: 
    do_stuff() 
    raise Somename 
+1

編集されました - 元の答えは、エラーメッセージを表示するためにprint.windows.printを使用しなければならないと思われるかもしれません。後であなたのレジャーの間にキャッチされたエラーを簡単に再現することができます。 – jkm

関連する問題