LoginSignup
1
2

More than 5 years have passed since last update.

Pythonについて vol09.try/except

Posted at

今回は例外処理(エラーハンドリング)です。JAVAで言うところのtry-catchですね。
例えばboto3を使って、AWS CLIを実行して何かエラーがあるとそこでスクリプトは停止してしまいます。
エラーが発生したら、その対処をして、後続に進めたい時にtry-exceptを使います。

try:
    aws.cli.hogehoge
except Exception as err:
    print('error is ### {0} ###'.format(err))

短い文ですが、単純にaws.cli.hogehogeを打ったときと出力が異なります。

try文を使う。

ちゃんとエラーハンドリングされる。

>>> try:
...     aws.cli.hogehoge
... except Exception as err:
...     print('error is ### {0} ###'.format(err))
...
error is ### name 'aws' is not defined ###

単純に実行。

Tracebackが表示される。

>>> aws.cli.hogehoge
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'aws' is not defined
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2