Menu
CoddyTech

处理错误

Coddy 货币转换器:Python 项目 课程的第 3 课,共 5 课。

处理错误是个好习惯。

在 Python 中,要引发带有错误消息的异常,我们会使用:

raise Exception("My error message")
challenge icon

挑战

简单

为 to_usd 函数添加错误处理,处理上述错误:

  • 不支持的货币:当货币不在 CURRENCIES 中时引发
  • Invalid amount:当请求的金额小于 0 时引发

查看测试用例,了解每种错误的错误消息格式!

亲手试试

CURRENCIES = {
    'USD': 1,
    'EUR': 1.06,
    'YEN': 0.0067,
    'GBP': 1.23,
    'AUD': 0.64,
    'CAD': 0.74
}


def to_usd(currency, amount):
    res = CURRENCIES[currency] * amount
    return res

货币转换器:Python 项目中的所有课

自己练习: Python 在线编译器