TypeError: exceptions must be old-style classes or derived from BaseException, not NoneTypeの対処法(Python2)
今回はTypeError: exceptions must be old-style classes or derived from BaseException, not NoneTypeはなぜ起きるのかについてご紹介いたします。
Python2でのみ起こるようです。
TypeError: exceptions must be old-style classes or derived from BaseException, not NoneTypeの対処法(Python2)
結論から言うと、TypeError: exceptions must be old-style classes or derived from BaseException, not NoneTypeはエラーハンドリングを行わないソースでraiseを使った際に何も指定しない場合に起こります。
言葉では分かりづらいので例を挙げます。
次のPythonのソースがあるとします。
特に難しい処理はしておりませんが、まずtryブロックの中でprint('test’)を実行した後、下のelse文の処理を行う処理です。
tryブロックの中でExceptionは発生しないので、「except Exception:」で例外をキャッチせず下のelse文のみ実行されます。
これをPython2で実行すると次のようになります。
else文の中のraiseで例外が発生しており、「TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType」と出ていますね。
試しに、raiseでBaseExceptionを指定してみましょう。
修正したソースが以下のソースです。
上記ソースの実行結果は次のようになります。
TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType」が出なくなりましたね。
exceptブロックの外でraiseを使う場合は、何かエラーのインスタンスなりを指定してやる必要があるのです。
ちなみに上記はPython2の場合でPython3では「RuntimeError: No active exception to reraise」となります。
終わりに
今回はTypeError: exceptions must be old-style classes or derived from BaseException, not NoneTypeはなぜ起きるのかについてご紹介いたしました。
ディスカッション
コメント一覧
まだ、コメントがありません