-1

Python でカスタム エラー例外を作成しようとしています。引数が辞書にない場合にエラーが発生するようにします_fetch_currencies()

カスタム エラー:

class CurrencyDoesntExistError:
    def __getcurr__(self):
        try:
            return _fetch_currencies()[self]
        except KeyError:
            raise CurrencyDoesntExistError()

関数にどのように書き込んだか:

def convert(amount, from_curr, to_curr, date=str(datetime.date.today())):
    """
    Returns the value obtained by converting the amount 'amount' of the 
    currency 'from_curr' to the currency 'to_curr' on date 'date'. If date is 
    not given, it defaults the current date.
    """
    try:    
        from_value = float(get_exrates(date)[from_curr])
        to_value = float(get_exrates(date)[to_curr])

        C = amount * (to_value / from_value)
        return C
    except CurrencyDoesntExistError:
        print('Currency does not exist')

現在、次のエラー メッセージが表示されます。

TypeError: catching classes that do not inherit from BaseException is not allowed

except KeyError:関数で使用convertすると実行されますが、このカスタムエラー例外を発生させる正しい方法は何ですか?

4

3 に答える 3

2

他の人がすでに言ったように、クラス定義に基本クラス参照がないという問題があります。

ただし、これは、同じ名前のモジュールとクラスがあり、クラスではなくモジュールをインポートした場合にも発生する可能性があります。

たとえば、モジュールとクラスは MyException と呼ばれます。

import MyException

このエラーが発生しますが、次のようになります。

from MyException import MyException

期待どおりに動作します。

于 2019-07-18T14:28:53.167 に答える