well go to the question. I make this query:
Puntuaciones.objects.filter(bar__id=b).get(usuario=v.usuario2)
This works perfect, but when i put this in a if statement, like this:
if(Puntuaciones.objects.filter(bar__id=b).get(usuario=v.usuario2)):
I have a problem, when the query returns a object Puntuaciones i haven't any problems, but when there isn't a result it throws me:
Exception Value: Puntuaciones matching query does not exist.
So my question is, How i can do a if statement for a query if this query can be unsuccessful.
I try with Q objects, with exists()(this just works for querysets... I dont know how make it work. Any suggestion? Thank you
get() is either returning an object or throws ObjectDoesNotExist exception, catch it with the help of try/except:
try:
Puntuaciones.objects.filter(bar__id=b).get(usuario=v.usuario2)
# do something if object was found
except Puntuaciones.DoesNotExist:
# do smth if nothing found
Another options is to use exists():
if Puntuaciones.objects.filter(bar__id=b, usuario=v.usuario2).exists():
# do something if object was found
I would suggest a try: except: pair. That way, when the exception is triggered, you will be in the appropriate location to perform the code. Note that you really should use the correct exception type in the setup. Note that if you want to skip processing in the except, you need to put in an explicit pass (python noop) statement. Otherwise you will get an indentation error.
try:
if(Puntuaciones.objects.filter(bar__id=b).get(usuario=v.usuario2)):
# put code in here
pass # dummy statement to be replaced by actual code.
except:
# Put exception code here.
pass
Related
Anyone can tell me about only try function is possible in exception handling in python
because i want to use only try function not exception method
Okay now i am editing the question because this is a bad practice..
Okay now i got to know about this is a bad practice so now please give this question to up and I am apologizing for this.
Usually, this is a bad practice. But here you go:
try:
<your code here>
except:
pass
This will try your code and if it fails then does nothing.
Example:
In Python, pass is a null statement. The interpreter does not ignore a pass statement, but nothing happens and the statement results in no operation. The pass statement is useful when you don't write the implementation of a function but you want to implement it in the future.
I have some exception handling code in python where two exceptions can be raised, the first one being a "superset" of the second one.
I.e. the following code summarizes what I need to do (and works fine)
try:
normal_execution_path()
except FirstError:
handle_first_error()
handle_second_error()
except SecondError:
handle_second_error()
But it requires me to abstract everything into independent functions for the code to remain clean and readable. I was hopping for some simpler syntax like:
try:
normal_execution_path()
except FirstError:
handle_first_error()
raise SecondError
except SecondError:
handle_second_error()
But this does not seem to work (SecondError does not get re-catched if it is raised inside this block). Is there anything doable in that direction though ?
If you wish to manually throw the second error to be handled, you can use nested try-catch blocks like these:
try:
normal_execution_path()
except FirstError:
try:
handle_first_error()
raise SecondError
except SecondError:
handle_second_error()
except SecondError:
handle_second_error()
Perhaps it is worth reviewing the code architecture. But for your particular case:
Create a generic class that handles this type of error. To inherit from it for the first and second error cases. Create a handler for this type of error. In the handler, check the first or second special case and process it with a waterfall.
class SupersetException(Exception):
pass
class FirstError(SupersetException):
pass
class SecondError(SupersetException):
pass
def normal_execution_path():
raise SecondError
def handle_superset_ex(state):
# Our waterfall
# We determine from whom the moment to start processing the exception.
if type(state) is FirstError:
handle_first_error()
# If not the first, the handler above will be skipped
handle_second_error()
try:
normal_execution_path()
except SupersetException as state:
handle_superset_ex(state)
Then just develop the idea.
I'm working with a special try-except-else block in python where I try to fetch an value and if I fail I try to create it to use later.
However, the creation process is not perfect (it actually fetches from the internet and might fail for several reasons) and I noticed that when this fails it is not raised. The only information I get is that the value is not defined
NameError: name 'value' is not defined
Since the error can be many, I would very much appreciate to see the full trackback for the error in the else clause
Please note: all tries can raise KeyError and the instantiation process cannot raise this error, it's always something else. Here is a sample code:
try:
value = _list[key]
except KeyError:
try:
number = kwargs['number'] # A number might be parsed via kwargs
except KeyError:
clean_everything()
value = None
raise KeyError('Value not found! ' +
'Need a number to create new instance!')
else:
value = Value(number=number) # This instantiation can raise other errors!
_list[homeTeam] = _listnumber[number] = value # Update lists for future reference.
finally:
print value
Anyone got any ideas on why the else clause is not raising? Is there a better way to write this?
Thanks,
EDIT: Added treatment for value inside the nested try.
This is leading me to believe that nested tries doesn't work as the nested errors will only be raised after the outer-most finally.
i.e. inner errors are raised only after the outer try is completed.
This might lead to a new question: how can I properly raise an error inside an except clause?
Trying to access value without first defining it indeed raises NameError. If KeyError is raised because key is not in _list, then value will never get defined in the try block. Because you redefine value in both of the except blocks, this should be OK there. However, your finally block does not redefine value before accessing it, so you would get a NameError there in the following cases:
value = _list[key] raises an error other than KeyError (e.g. NameError when _list is not defined)
clean_everything() raises any error
value = Value(number=number) raises any error
You can define value before the try block so that it is always defined no matter what happens inside the try block.
I am developing a program in python and have reached a point I don't know how to solve.
My intention is to use a with statement, an avoid the usage of try/except.
So far, my idea is being able to use the continue statement as it would be used inside the except. However, I don't seem to succeed.
Let's supposse this is my code:
def A(object):
def __enter__:
return self
def __exit__:
return True
with A():
print "Ok"
raise Exception("Excp")
print "I want to get here"
print "Outside"
Reading the docs I have found out that by returning True inside the __exit__ method, I can prevent the exception from passing, as with the pass statement. However, this will immediately skip everything left to do in the with, which I'm trying to avoid as I want everything to be executed, even if an exception is raised.
So far I haven't been able to find a way to do this. Any advice would be appreciated.
Thank you very much.
It's not possible.
The only two options are (a) let the exception propagate by returning a false-y value or (b) swallow the exception by returning True. There is no way to resume the code block from where the exception was thrown. Either way, your with block is over.
You can't. The with statement's purpose is to handle cleanup automatically (which is why exceptions can be suppressed when exiting it), not to act as Visual Basic's infamous On Error Resume Next.
If you want to continue the execution of a block after an exception is raised, you need to wrap whatever raises the exception in a try/except statement.
Though most of the answers are correct, I'm afraid none suits my problem (I know I didn't provide my whole code, sorry about that).
I've solved the problem taking another approach. I wanted to be able to handle a NameError ("variable not declared") inside a With. If that occurred, I would look inside my object for that variable, and continue.
I'm now using globals() to declare the variable. It's not the best, but it actually works and let's the with continue as no exception is being risen.
Thank you all!
I have an object that may or may not exist. Due to this fact I have wrapped the statement in a try / except block.
try:
generic_type = ContentType.objects.get_for_model(myentity)
my_object = MyObject.objects.filter(content_type__pk=generic_type.id, object_id=myentity.id)[0]
except:
The reason I ask is because I have nothing to put in the Except condition in this situation, but django/python requires it.
Is this the proper way to handle this situation? If it is, what should I put after the Except?
You can use the pass statement anywhere a statement is required when you want to do nothing, although you should specify the actual exception to catch.
except WhateverExceptionGetsRaised:
pass
If you are retrieving an object based on "PK" then it is only going to return one object. There isn't a need for multiple filters. Instead of:
my_object = MyObject.objects.filter(content_type__pk=generic_type.id, object_id=myentity.id)[0]
You can use:
my_object = MyObject.objects.get(content_type__pk=generic_type.id, '')
You would use this if you want it to return nothing hence the double single quotes if it fails to get the first object specified. This may be a more concise answer than an try/except pattern. Also, using:
filter()[0] vs. get()
will both return one object, but filter()[0] returns a QuerySet object type, where as get() returns the object only, so this is another thing to consider.