12
9

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 5 years have passed since last update.

【Pythonメモ 】例外を呼び出し元に送信する方法

Last updated at Posted at 2018-06-10

・関数内のexcept内で、raiseを行うことで例外を呼び出し元に送信することができる。
 

呼び出し元に例外を送信するサンプル

hoge.py
# !/usr/bin/python
# -*- Coding: utf-8 -*-


class Hoge(object):

    def huga():
        try:
            raise TypeError('TYPE ERROR!')
        except Exception as e:
            raise           # 呼び出し元に送信

    try:
        huga()
        
    except Exception as e:
        print(type(e))      # 1回目のエラー出力

・関数内でエラーを出力して、呼び出し元に例外を送信することも可能。

関数内でエラー出力後、呼び出し元に例外を送信するサンプル

hoge.py
# !/usr/bin/python
# -*- Coding: utf-8 -*-


class Hoge(object):

    def huga():
        try:
            raise TypeError('TYPE ERROR!')
        except Exception as e:
            print(type(e))  # 1回目のエラー出力
            raise           # 呼び出し元に再送

    try:
        huga()
        
    except Exception as e:
        print(type(e))      # 2回目のエラー出力

上記のexcept内にloggingを使用すれば、関数内のローカル変数をログに出力を行い、呼び出し元で別のログ出力することができる。

12
9
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
12
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?