For example I have script like this
def form_valid:
temp = form.save(commit=False)
try:
temp.contents = makecontents()
except:
messages.error(self.request, error)
return self.render_to_response(self.get_context_data(form=form))
messages.success(self.request, self.success_message)
return super().form_valid(form)
def makecontents():
if (if works well):
return "this is my contents"
else:
return "this is error!!"
So, my basic idea is when makecontents() success it returns the string s and set this as member of model instance.
However makecontents() failed , I want to return the error to form_valid.
So, maybe ,, I should change return "this is error!!" somehow..
Is it possible? , or my idea is wrong??
you could use anraise '<an Exception Type>("error message")' to raise an Error, and then except Exception as e: to get the exception message:
def makecontents(works_well):
try:
if (works_well):
return "this is my contents"
else:
raise SyntaxError("this is an error")
except Exception as e:
return str(e)
print(makecontents(works_well=False).__repr__())
output:
"this is an error"
Related
This is a python script that runs in a Django environment by Celery. I need to create a catch the 'rest of the errors' and raise an exception so Celery will send a email on that exception.
Would this be the best way?
for thread in thread_batch:
try:
obj = query_set.get(thread_id=thread['thread_id'])
for key, value in thread.iteritems():
setattr(obj, key, value)
obj.unanswered = True
except ThreadVault.DoesNotExist:
obj = ThreadVault(**thread)
except:
raise Exception("There has been a unknown error in the database")
obj.save()
Yes, and empty except will catch any exception different from ThreadVault.DoesNotExist (in this case). But you can improve your code a little more.
Try always to put the less code possible inside the try block. You code could be:
for thread in thread_batch:
try:
obj = query_set.get(thread_id=thread['thread_id'])
except ThreadVault.DoesNotExist:
obj = ThreadVault(**thread)
except:
raise Exception("There has been a unknown error in the database")
else: # Note we add the else statement here.
for key, value in thread.iteritems():
setattr(obj, key, value)
obj.unanswered = True
# Since save function also hits the database
# it should be within a try block as well.
try:
obj.save()
except:
raise Exception("There has been a unknown error in the database")
I was wondering if its possible to write a handling exceptions like with 2 or more except with different task to do.
I'm using Django==1.6.1 and Python 2.7
try:
foo_instance = foo.objects.get(field_name='unknown')
except foo.DoesNotExist:
new_rec = foo.objects.create(field_name='unknown')
new_rec.save()
foo_instance = foo.objects.get(field_name='unknown')
except foo.MultipleObjectsReturned:
foo_list = foo.objects.filter(field_name='unknown')
for record in foo_list[1:]:
print 'Deleting foo id: ', record.id
record.delete()
foo_instance = foo.objects.get(field_name='unknown')
You could use multiple try: except: but in your current scenario Why don't you use get_or_create ?
try: expect: contain all errors on 'Exception'. for this syntax is all
except Exception as e:
get_or_create(defaults=None, **kwargs)
A convenience method for looking up an object with the given kwargs
(may be empty if your model has defaults for all fields), creating one
if necessary.
Returns a tuple of (object, created), where object is the retrieved or
created object and created is a boolean specifying whether a new
object was created.
This reduces your above code to -
obj, created = foo.objects.get_or_create(field_name='unknown')
if created:
obj.save()
I think get_or_create raises IntegrityError or MultipleObjectsReturned, to handle those simply wrap it in a try:
try:
obj, created = foo.objects.get_or_create(field_name='unknown')
if created:
obj.save()
except IntegrityError:
#do something
except MultipleObjectsReturned:
#do something else
except Exception as e:
raise e
I have a function with a try catch block where I have:
def testfunction():
try:
good = myfunction()
return good
except ExceptionOne:
error="Error ExceptionOne".
return error
except ExceptionTwo:
error="Error ExceptionTwo".
return error
except ExceptionThree:
error="Error ExceptionThree".
return error
Is there a way such that I could structure this in such a way where have a single return statement for all the exceptions?
What about something like:
def testfunction():
try:
good = myfunction() # or `return myfunction()` if the case is actually this simple
except (ExceptionOne, ExceptionTwo, ExceptionThree) as err:
error = 'Error %s' % err.__class__.__name__
return error
return good
Of course, I'm not exactly sure what the purpose of this is. Why not just let the exception propogate and handle it higher up? As it is, you need logic to check the return value to see if it's good or not anyway, I think it would be cleaner if that logic was bound up in exception handling rather than in type checking or string value checking ...
How can I catch AttributeError from this line and print message to the user, let's say "you can't change class="post" "
I tried with try, except AttributeError, raise, print but it's always returning nothing.
That's what I did:
re.search() returns None if no position in the string matches the pattern. Check for None and raise an exception:
post_start = re.search('<div class="post">', html)
if post_start is None:
raise AttributeError('you can\'t change <div class="post">')
In my application users enter a url and I try to open the link and get the title of the page. But I realized that there can be many different kinds of errors, including unicode characters or newlines in titles and AttributeError and IOError. I first tried to catch each error, but now in case of a url fetch error I want to redirect to an error page where the user will enter the title manually. How do I catch all possible errors? This is the code I have now:
title = "title"
try:
soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))
title = str(soup.html.head.title.string)
if title == "404 Not Found":
self.redirect("/urlparseerror")
elif title == "403 - Forbidden":
self.redirect("/urlparseerror")
else:
title = str(soup.html.head.title.string).lstrip("\r\n").rstrip("\r\n")
except UnicodeDecodeError:
self.redirect("/urlparseerror?error=UnicodeDecodeError")
except AttributeError:
self.redirect("/urlparseerror?error=AttributeError")
#https url:
except IOError:
self.redirect("/urlparseerror?error=IOError")
#I tried this else clause to catch any other error
#but it does not work
#this is executed when none of the errors above is true:
#
#else:
# self.redirect("/urlparseerror?error=some-unknown-error-caught-by-else")
UPDATE
As suggested by #Wooble in the comments I added try...except while writing the title to database:
try:
new_item = Main(
....
title = unicode(title, "utf-8"))
new_item.put()
except UnicodeDecodeError:
self.redirect("/urlparseerror?error=UnicodeDecodeError")
This works. Although the out-of-range character —is still in title according to the logging info:
***title: 7.2. re — Regular expression operations — Python v2.7.1 documentation**
Do you know why?
You can use except without specifying any type to catch all exceptions.
From the python docs http://docs.python.org/tutorial/errors.html:
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as (errno, strerror):
print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
The last except will catch any exception that has not been caught before (i.e. a Exception which is not of IOError or ValueError.)
You can use the top level exception type Exception, which will catch any exception that has not been caught before.
http://docs.python.org/library/exceptions.html#exception-hierarchy
try:
soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))
title = str(soup.html.head.title.string)
if title == "404 Not Found":
self.redirect("/urlparseerror")
elif title == "403 - Forbidden":
self.redirect("/urlparseerror")
else:
title = str(soup.html.head.title.string).lstrip("\r\n").rstrip("\r\n")
except UnicodeDecodeError:
self.redirect("/urlparseerror?error=UnicodeDecodeError")
except AttributeError:
self.redirect("/urlparseerror?error=AttributeError")
#https url:
except IOError:
self.redirect("/urlparseerror?error=IOError")
except Exception, ex:
print "Exception caught: %s" % ex.__class__.__name__