【问题标题】:how to throw an error if certain condition evaluates to true如果某些条件评估为真,如何抛出错误
【发布时间】:2022-01-14 05:19:02
【问题描述】:

我有以下代码块:

try:
    if str(symbol.args[0]) != str(expr.args[0]):
        print('true')
        raise SyntaxError('====error')
except:
    pass

在这里,如果某些条件为真,我正在尝试提高 Syntax error。我正在测试此代码块,我可以看到打印出“真”,这意味着条件满足,但即使在那之后,代码也不会抛出语法错误。

我试图理解上面的代码有什么问题。

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    您将 pass 放入正在吞噬异常的 except: 块中。从 try-except 块中删除代码或将 pass 更改为 raise

    【讨论】:

    • 如果 except 块包含的所有内容都是 raise,那么首先使用 try/except 是没有意义的。
    • 正确,但如果他决定对错误采取行动,他将不得不再次引发异常而不是通过,所以只想指出这一点。
    【解决方案2】:

    上面的答案是指向问题,我只是想举一些例子来帮助你更好地理解try/except是如何工作的:

    # Just raise an exception (no try/except is needed)
    if 1 != 2:
        raise ValueError("Values do not match")
    
    # Catch an exception and handle it
    a = "1"
    b = 2
    try:
        a += b
    except TypeError:
        print("Cannot add an int to a str")
    
    # Catch an exception, do something about it and re-raise it
    a = "1"
    b = 2
    try:
        a += b
    except TypeError:
        print("Got to add an int to a str. I'm re-raising the exception")
        raise
    

    try/except 后面也可以跟 elsefinally,您可以在此处查看更多信息:try-except-else-finally

    【讨论】:

      猜你喜欢
      • 2018-02-24
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多