本文介绍了如果给定的字符串与某些格式不匹配,则会引发哪种异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是的追踪。

给定一个ISBN号码,例如 3-528-03851-5 如果传入的字符串与格式X-XXX-XXXXX-X格式不符,我应该提出哪种异常类型?

Given a ISBN number, e.g. 3-528-03851-5 which exception type should I raise if the passed in string doesn't match the format X-XXX-XXXXX-X?

推荐答案

提高 ValueError

几乎是说你给我一个没有意义的价值的标准方式。例如:

It's pretty much the standard way of saying "you've given me a value that doesn't make sense". For example:


>>> int("a")
Traceback (most recent call last):
  File "", line 1, in
ValueError: invalid literal for int() with base 10: 'a'
>>> import shlex; shlex.split("'")
Traceback (most recent call last):
   ...
ValueError: No closing quotation

与一个 TypeError 对比,当类型不正确时,它引发:

Contrast this with a TypeError, which is raised when a type is incorrect:


>>> d = {}
>>> d[{}]
Traceback (most recent call last):
  File "", line 1, in
TypeError: unhashable type: 'dict'

这篇关于如果给定的字符串与某些格式不匹配,则会引发哪种异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 07:22