Py学习  »  Python

python:从函数返回异常

Subbeh • 5 年前 • 1305 次点击  

假设我有以下功能:

def test():
  ...
  if x['error']:
    raise

这将引发一个异常,无论 x['error'] 是否已定义。

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

def test():
  ...
  try:
    if x['error']:
      raise
  except:
    return

如果定义了一个特定的值,我如何测试它并返回一个异常;如果没有定义,我如何成功返回?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38697
 
1305 次点击  
文章 [ 3 ]  |  最新文章 5 年前
Black Thunder
Reply   •   1 楼
Black Thunder    6 年前

如果要以字符串形式返回错误:

>>> def test():
    try:
        if x['error']:raise
    except Exception as err:
        return err

>>> test()
NameError("name 'x' is not defined",)

如果希望发生错误:

>>> def test():
    try:
        if x['error']:raise
    except:
        raise

>>> test()
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    test()
  File "<pyshell#19>", line 3, in test
    if x['error']:raise
NameError: name 'x' is not defined
vinay
Reply   •   2 楼
vinay    6 年前

试试这个

def check_not_exist(d,k):
   #if keys exists in dict,raise it
   if k in d:
     raise
   else:
     return True
Philip DiSarro
Reply   •   3 楼
Philip DiSarro    6 年前
def test():
  ...
  if x.get(‘error’):
    raise

使用字典的内置功能,可以避免无意中引发错误。 get 功能。GET将返回 None 如果指定键处的值不存在,则不会引发异常。