how to throw an error if certain condition evaluates to true - python-3.x

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.

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

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

Related

Python Try Except when a list is null

I've been searching for my problem here, but i can't find the exact answer to my problem.
I call a sympy function ( solve() ). This function can return a full list or an empty list.
I call this piece of code inside a while:
try:
sol = solve([eq1,eq2],[r,s])
rB = bin(abs(sol[0][0]))
sB = bin(abs(sol[0][1]))
stop = True
r = rB[2:len(rB)]
s = sB[2:len(sB)]
P = int("0b"+r+s,2)
Q = int("0b"+s+r,2)
print(P*Q == pubKey.n)
print("P = {}".format(P))
print("Q = {}".format(Q))
break
except ValueError:
pass
What i want is:
if the solve() returns an empty list, just pass. And if the solve() returns a full list, keep with the execution. The solve will be returning empty list until i find the right value.
This can be reached by checking sol[0][0], if there's a non-empty list this will work, but if the list is empty, this will throw an error (null pointer) i want try to flag it and pass.
What i'm having now is that when sol is empty, it tries to get sol[0][0], and ofc this throws an error that's not being catched by the try, and the whole code stops.
Anyone knows a solution for that? I'm not using try correctly?
Set sol in the beginning of each loop to some value and check it in the except clause
about else
try/except has an else which will be run the try block did not raise an Exception
and for has an else clause for when it was not broken out of!
for foo in iterable:
# set value so the name will be available
# can be set prior to the loop, but this clears it on each iteration
# which seems more desirable for your case
sol = None
try:
"logic here"
except Exception:
if isinstance(sol, list):
"case where sol is a list and not None"
# pass is implied
else: # did not raise an Exception
break
else: # did not break out of for loop
raise Exception("for loop was not broken out of!")

Catching Outer Exceptions in Python

My code tries to do something, but it triggers an Error... which triggers another Error. So, the error message looks something like this:
SillyError: you can`t do that becuz blablabla
The above exception was the direct cause of the following exception:
LoopyError: you can`t do that becuz blobloblo
I want to create a try except block that only catches this specific duo of errors. However, I am only able to catch the first one, because once I do, the second one never gets a chance to trigger.
This other question is about catching either exception, but I want to catch only if both are triggered in succession. Is there a way?
If you have a try\except, you will always catch the error based on the outer exception. However you do have the option to pass on any exceptions you don't want to process.
In this code, the ZeroDivisionError is caught and wrapped in another exception which is then caught by the calling code. The calling code checks for the inner exception and decides whether to re-raise the exception up the stack.
def xtest():
try:
a = 1/0 # exception - division by zero
except ZeroDivisionError as e:
raise Exception("Outer Exception") from e # wrap exception (e not needed for wrap)
try:
xtest()
except Exception as ex:
print(ex) # Outer Exception
print(ex.__cause__) # division by zero
if (str(ex) == "Outer Exception" and str(ex.__cause__) == "division by zero"):
print("Got both exceptions")
else:
raise # pass exception up the stack
Just for completion, you can do the check based on the exception class name also:
if (type(ex).__name__ == "Exception" and type(ex.__cause__).__name__ == "ZeroDivisionError"):
print("Got both exceptions")
#ShadowRanger pointed out that it may be quicker to just check the class type instead of the class name:
if (type(ex) == Exception and type(ex.__cause__) == ZeroDivisionError):
print("Got both exceptions")

How to exit from a function [duplicate]

I am starting to learn Python, and I wrote a very simple code to practice try/except.
Here is the code:
a = float(input('num1: '))
b = float(input('num2: '))
try:
result = a / b
except ValueError as e:
print ('error type: ', type (e))
print(result)
Whenever I enter a letter as a number, the print in except is working, but the code crashes.
ZeroDivisionError & TypeError are working, but ValueError is not.
I even put inputs in separate try/except and it is still not working.
How can I handle this error here, and in the real app?
The crash is occurring before you enter the try block. It does not print the error in the except block if you enter a letter with your current code.
Simply putting the input section in a separate try block wouldn't catch it - you need an except block related to the try within which the error is happening, e.g.
try:
a = float(input('num1: '))
b = float(input('num2: '))
except ValueError as e:
print ('Value Error')
try:
result = a / b
except ZeroDivisionError as e:
print ('Zero DivisionError')
print(result)
Alternatively, you could put the input and division all within the try block and catch with your current reporting:
try:
a = float(input('num1: '))
b = float(input('num2: '))
result = a / b
except ValueError as e:
print ('error type: ', type (e))
print(result)
EDIT: Note that if any error does occur in either of these, it will cause further errors later on. You're better off going with the second option, but moving the print(result) into the try block. That's the only time it will be defined.

Python3 missing exception when looping

I have to define an attribute in a class and I would like to manage error in the most pythonic way.
Here is the code I have tried so far. I can't figure out why I can not "reach" the exception in the following code.
# global variable to be used in the example
my_dict = {"key1": {"property": 10}, "key2": {}}
class Test(object):
#property
def my_attribute(self):
try:
return self._my_attribute
except AttributeError:
self._my_attribute = {}
for key, value in my_dict.items():
print(key)
self._my_attribute[key] = value['property']
except Exception:
print('error')
# I would like to manage my error here with a log or something
print("I am not reaching here")
finally:
return self._my_attribute
if __name__ == '__main__':
Test().my_attribute
I expected to reach the Exception case in the second iteration of the for loop since it is a KeyError ("key2" has no "property"). But it just passes by it. In this example, if the script is run, it does not print "I am not reaching here". Could anyone explain why I am seeing this wrong? Thanks!
The potential KeyError in self._my_attribute[key] = value['property'] is not covered by the except Exception block. Once it is raised the finally block is executed (as a matter of fact the finally block is always executed, regardless of an exception being raised or even handled). This can be easily verified by using a step-by-step debugger or with a simple print('finally') inside the finally block.
This is (among other reasons) why try blocks should be as minimal as possible. If you know that line might raise a KeyError then explicitly try-except it:
for key, value in my_dict.items():
print(key)
try:
self._my_attribute[key] = value['property']
except KeyError as e:
print('Key ', e, 'does not exist')

Unwanted SyntaxError Exception in Python 3

I am trying harder and harder to understand why this SyntaxError exception is being thrown every time but still unable to figure out what actually triggers this exception.
Below is the code with the error thrown :
try:
f = open('file.txt')
s = f.readline()
print(str(s))
except OSError as err:
print('There is some problem')
This is the Exception which is thrown:
File "<ipython-input-44-2def6d980129>", line 5
except OSError as err:
^ SyntaxError: invalid syntax
I know this is maybe regarded as a beginner's issue, but I would rather appreciate if you a could just drop a constructive answer or a comment.
Thank you.
in python you have do indentation,with you have a inner value something like class to method or loop with do something inside loop
So your code must be like this :
try:
f = open('name.txt')
s = str(f.readline())
print(s)
except OSError as err:
print(err) #and you cant just leave this line empty because you must do something with excepted error
Youyr code is not indented correctly.
Example:
try:
f = open('name.txt')
s = str(f.readline())
print(s)
except OSError as err:
pass
Indentation, Except should be in line with try

Resources