[Django]-Django Try Except Not Working

10👍

Please modify the code to this, run it and tell us what exception you are getting:

try:
    print "what"
    newClassName = CourseNameAndCodeAssociation.objects.get(departmentCode__iexact =         nameAndNumberStore[0])
    print newClassName  
except Exception as e:
    print "HAHA"
    print e

Also, it would probably help to have a debugger installed on your box. I can recommend Eclipse in combination with PyDev, but that is a personal choice. There are lots of great options out there.

Eclipse IDE – download the basic Java version of 120MB

then install this plugin on top of it – Pydev

2👍

Change it to:

except CourseNameAndCodeAssociation.DoesNotExist:

Each model you create gets its own DoesNotExist exception that extends core ObjectDoesNotExist exception.

Also the best approach is to only use tryexcept around the precise line that you expect to fail. A more pythonic way to write what you have there would be:

department_code = name_and_number_store[0]
class_names = CourseNameAndCodeAssociation.objects.all()
try:
    new_class_name = class_names.get(departmentCode__iexact=department_code)
except CourseNameAndCodeAssociation.DoesNotExist:
    print "HAHA"
else:
    search_term = u'%s %s' % (new_class_name.departmentName,
                              name_and_number_store[1])
    name_and_number_store = modify_search_term(search_term)
    url_store = modify_url(name_and_number_store)
    soup = get_html(url_store)
    store_of_books = scrape(soup, name_and_number_store)

Please also note that the convention in Python is to use lowercase_underscored_names for variables, attributes and function names and CamelCaseNames for class names (instance names are either variables or attributes).

👤patrys

Leave a comment