例外をスローする可能性のある行がたくさんありますが、それでも次の行に続くはずです。例外をスローする可能性のあるすべてのステートメントを個別にキャッチしようとせずにこれを行うにはどうすればよいですか?
try:
this_may_cause_an_exception()
but_I_still_wanna_run_this()
and_this()
and_also_this()
except Exception, e:
logging.exception('An error maybe occured in one of first occuring functions causing the others not to be executed. Locals: {locals}'.format(locals=locals()))
上記のコードを見てみましょう。すべての関数が例外をスローする可能性がありますが、例外をスローしたかどうかに関係なく、次の関数を実行する必要があります。それを行う良い方法はありますか?
私はこれをしたくありません:
try:
this_may_cause_an_exception()
except:
pass
try:
but_I_still_wanna_run_this()
except:
pass
try:
and_this()
except:
pass
try:
and_also_this()
except:
pass
例外が重大な場合にのみ、例外の後もコードを実行し続ける必要があると思います(コンピューターが燃えるか、システム全体が台無しになり、プログラム全体が停止するはずですが、接続などの多くの小さなことでも例外がスローされます失敗など)通常、例外処理に問題はありませんが、この場合、小さなことで簡単に例外をスローするサードパーティのライブラリを使用しています.
m4spy の回答を見た後、例外が発生した場合でも関数内のすべての行を実行できるようにするデコレータを使用することは不可能だと思いました。
このようなものはクールです:
def silent_log_exceptions(func):
@wraps(func)
def _wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
except Exception:
logging.exception('...')
some_special_python_keyword # which causes it to continue executing the next line
return _wrapper
またはこのようなもの:
def silent_log_exceptions(func):
@wraps(func)
def _wrapper(*args, **kwargs):
for line in func(*args, **kwargs):
try:
exec line
except Exception:
logging.exception('...')
return _wrapper
@silent_log_exceptions
def save_tweets():
a = requests.get('http://twitter.com)
x = parse(a)
bla = x * x