0

I have below code block:

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

Here I am trying to raise Syntax error if certain condition is true.I am testing this code block, I can see 'true' is getting printed which means condition is met but even after that also the code is not throwing syntax error.

I am trying to understand what is wrong in the above code.

Dcook
  • 899
  • 7
  • 32

2 Answers2

3

You're putting pass in the except: block which is swallowing the exception. Either remove the code from the try-except block or change pass to raise

qTzz
  • 126
  • 6
  • 1
    If all the `except` block contains is a `raise`, there's no point in having try/except in the first place. – Mark Ransom Jan 14 '22 at 05:30
  • Correct, but if he did decide to act on the error he would have to raise the exception again instead of pass so just wanted to point that out. – qTzz Jan 14 '22 at 05:32
0

Above answer is pointing the issue, I just want to give some examples to help you better understand how try/except works:

# 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 can also be followed by else and finally, you can check more about these here: try-except-else-finally

Dan Constantinescu
  • 1,426
  • 1
  • 7
  • 11