例外を処理せずに try-except を実行したい場合、Python でどのように実行しますか?
次の方法は正しいですか?
try:
shutil.rmtree(path)
except:
pass
例外を処理せずに try-except を実行したい場合、Python でどのように実行しますか?
次の方法は正しいですか?
try:
shutil.rmtree(path)
except:
pass
It's generally considered best-practice to only catch the errors you are interested in. In the case of shutil.rmtree
it's probably OSError
:
>>> shutil.rmtree("/fake/dir")
Traceback (most recent call last):
[...]
OSError: [Errno 2] No such file or directory: '/fake/dir'
If you want to silently ignore that error, you would do:
try:
shutil.rmtree(path)
except OSError:
pass
Why? Say you (somehow) accidently pass the function an integer instead of a string, like:
shutil.rmtree(2)
It will give the error "TypeError: coercing to Unicode: need string or buffer, int found" - you probably don't want to ignore that, which can be difficult to debug.
If you definitely want to ignore all errors, catch Exception
rather than a bare except:
statement. Again, why?
Not specifying an exception catches every exception, including the SystemExit
exception which for example sys.exit()
uses:
>>> try:
... sys.exit(1)
... except:
... pass
...
>>>
Compare this to the following, which correctly exits:
>>> try:
... sys.exit(1)
... except Exception:
... pass
...
shell:~$
If you want to write ever better behaving code, the OSError
exception can represent various errors, but in the example above we only want to ignore Errno 2
, so we could be even more specific:
import errno
try:
shutil.rmtree(path)
except OSError as e:
if e.errno != errno.ENOENT:
# ignore "No such file or directory", but re-raise other errors
raise
例外を処理せずにtrycatchを実行したい場合、Pythonでどのように実行しますか?
それはあなたが「扱う」とはどういう意味かによります。
何もせずにそれをキャッチするつもりなら、あなたが投稿したコードは機能します。
例外がスタックを上るのを止めずに例外に対してアクションを実行したい場合は、次のようなものが必要です。
try:
do_something()
except:
handle_exception()
raise #re-raise the exact same exception that was thrown
完全を期すために:
>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print("division by zero!")
... else:
... print("result is", result)
... finally:
... print("executing finally clause")
また、次のように例外をキャプチャできることにも注意してください。
>>> try:
... this_fails()
... except ZeroDivisionError as err:
... print("Handling run-time error:", err)
...そして、次のように例外を再発生させます。
>>> try:
... raise NameError('HiThere')
... except NameError:
... print('An exception flew by!')
... raise
また、複数の例外タイプを括弧で囲まれたタプルとして処理できます。
try:
i_might_fail()
except (ValueError, TypeError) as ex:
print('I failed with: ', ex)
...または個別のexcept節として:
try:
i_might_fail()
except ValueError:
print('handling a ValueError...')
except TypeError:
print('handling a TypeError...')
... python チュートリアルを参照してください。
例外を適切に無視する方法は?
これにはいくつかの方法があります。
ただし、例の選択には、一般的なケースをカバーしていない単純なソリューションがあります。
それ以外の
try:
shutil.rmtree(path)
except:
pass
これを行う:
shutil.rmtree(path, ignore_errors=True)
これは に固有の引数shutil.rmtree
です。次のようにしてヘルプを表示できます。また、エラーに関する機能も使用できることがわかります。
>>> import shutil
>>> help(shutil.rmtree)
これは例の狭いケースのみをカバーしているため、これらのキーワード引数が存在しない場合にこれを処理する方法をさらに示します。
上記は例の狭いケースのみをカバーしているため、これらのキーワード引数が存在しない場合にこれを処理する方法をさらに示します。
suppress
コンテキスト マネージャーをインポートできます。
from contextlib import suppress
ただし、最も具体的な例外のみを抑制します。
with suppress(FileNotFoundError):
shutil.rmtree(path)
黙って無視しFileNotFoundError
ます:
>>> with suppress(FileNotFoundError):
... shutil.rmtree('bajkjbkdlsjfljsf')
...
>>>
ドキュメントから:
例外を完全に抑制する他のメカニズムと同様に、このコンテキスト マネージャーは、プログラムの実行を黙って続行することが正しいことが知られている非常に特定のエラーをカバーするためにのみ使用する必要があります。
suppress
とFileNotFoundError
は Python 3 でのみ使用できることに注意してください。
コードを Python 2 でも動作させたい場合は、次のセクションを参照してください。
例外を処理せずに try/except を実行したい場合、Python でどのように実行しますか?
次の方法は正しいですか?
try : shutil.rmtree ( path ) except : pass
Python 2 互換コードpass
の場合、ノーオペレーションのステートメントを持つ正しい方法です。しかし、bare を実行するときは、 which includes 、、およびexcept:
を実行するのと同じであり、一般に、これらのものをキャッチしたくありません。except BaseException:
GeneratorExit
KeyboardInterrupt
SystemExit
実際、例外の名前はできるだけ具体的にする必要があります。
Python (2) の例外階層の一部を次に示します。ご覧のとおり、より一般的な例外をキャッチすると、予期しない問題を隠すことができます。
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StandardError
| +-- BufferError
| +-- ArithmeticError
| | +-- FloatingPointError
| | +-- OverflowError
| | +-- ZeroDivisionError
| +-- AssertionError
| +-- AttributeError
| +-- EnvironmentError
| | +-- IOError
| | +-- OSError
| | +-- WindowsError (Windows)
| | +-- VMSError (VMS)
| +-- EOFError
... and so on
おそらく、ここで OSError をキャッチしたいと思うでしょう。気にしない例外は、ディレクトリがない場合です。
ライブラリから特定のエラー番号を取得しerrno
、それがない場合は再発生させることができます。
import errno
try:
shutil.rmtree(path)
except OSError as error:
if error.errno == errno.ENOENT: # no such file or directory
pass
else: # we had an OSError we didn't expect, so reraise it
raise
ベアレイズは元の例外を発生させることに注意してください。これはおそらく、この場合に必要なものです。pass
例外処理でコードを明示的に使用する必要がないため、より簡潔に記述します。
try:
shutil.rmtree(path)
except OSError as error:
if error.errno != errno.ENOENT: # no such file or directory
raise
try:
doSomething()
except Exception:
pass
else:
stuffDoneIf()
TryClauseSucceeds()
参考までに、else 句はすべての例外の後に行くことができ、try のコードが例外を引き起こさない場合にのみ実行されます。
例外を処理せずに単に try catch を実行したい場合、Python でどのように実行しますか?
これは、例外が何であるかを出力するのに役立ちます:(つまり、例外を処理せずに catch を実行して、例外を出力します)。
import sys
try:
doSomething()
except:
print "Unexpected error:", sys.exc_info()[0]
Python では、他の言語と同様に例外を処理しますが、違いは構文の違いです。たとえば、
try:
#Your code in which exception can occur
except <here we can put in a particular exception name>:
# We can call that exception here also, like ZeroDivisionError()
# now your code
# We can put in a finally block also
finally:
# Your code...