猿问

python:从函数返回异常

假设我有以下功能:


def test():

  ...

  if x['error']:

    raise

无论是否x['error']定义,这都会引发异常。


相反,如果我尝试这个,它不会抛出任何异常:


def test():

  ...

  try:

    if x['error']:

      raise

  except:

    return

如何测试特定值并在定义时返回异常,如果未定义则成功返回?


蛊毒传说
浏览 242回答 3
3回答

米琪卡哇伊

def test():  ...  if x.get(‘error’):    raise您可以使用字典的内置get函数避免无意中引发错误。None如果指定键处的值不存在,则Get 将返回而不是抛出异常。

qq_遁去的一_1

如果要将错误作为字符串返回:>>> def test():&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; if x['error']:raise&nbsp; &nbsp; except Exception as err:&nbsp; &nbsp; &nbsp; &nbsp; return err>>> test()NameError("name 'x' is not defined",)如果要发生错误:>>> def test():&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; if x['error']:raise&nbsp; &nbsp; except:&nbsp; &nbsp; &nbsp; &nbsp; raise>>> test()Traceback (most recent call last):&nbsp; File "<pyshell#20>", line 1, in <module>&nbsp; &nbsp; test()&nbsp; File "<pyshell#19>", line 3, in test&nbsp; &nbsp; if x['error']:raiseNameError: name 'x' is not defined

慕娘9325324

试试这个def check_not_exist(d,k):&nbsp; &nbsp;#if keys exists in dict,raise it&nbsp; &nbsp;if k in d:&nbsp; &nbsp; &nbsp;raise&nbsp; &nbsp;else:&nbsp; &nbsp; &nbsp;return True
随时随地看视频慕课网APP

相关分类

Python
我要回答