0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Pythonで例外処理を関数化

Posted at

背景

自作のスクレイピングツール、よく途中でコケて最初からやり直し、
になることが多いので、例外処理を追加したいと思い作成。
作成したところ思ったより汎用性が高いものができた気がするので、備忘も兼ねてメモ。

関数

import sys


def try_func(func, *args):
    print(f'{func}を試みます')
    try:
        func(*args)
        print(f'{func}が実行されました')
    except Exception as e:
        print(e)
        print(type(e))
        print('実行中にエラーになりました')
        print('手動で継続する場合、手動で調整した後yを、中止する場合はn(y以外)を入力してください')
        flg = input('"y"or"n":')
        if flg == 'y':
            print('継続します')
            return
        else:
            print('中止します')
            sys.exit()


def test_func(a, b):
    result = a / b
    print('test_funcが実行されます')
    print(result)


if __name__ == '__main__':
    try_func(test_func, 6, 0)
    try_func(test_func, 6, 3)
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?