-2

In some cases, the attribute will be there, and in others, it will not. I'm trying to check for an error in advance so my program will not fail. I'm currently using this code:

 if stock.find_all("option") != AttributeError:
    all_sizes = stock.find_all("option")
else:
    print "Desired item has sold out"

Attempting to check for an error beforehand, however, I still get the following error.

if stock.find_all("option") != AttributeError:
AttributeError: 'NoneType' object has no attribute 'find_all'

Instead of the error and ending my program, I want it to simply print the message then terminate.

Colin
  • 151
  • 1
  • 1
  • 8
  • 1
    `stock` is `None`, not the return value of `stock.find_all()`. – Martijn Pieters Apr 03 '18 at 16:55
  • 1
    The error is pretty common, have you searched for it yet? All you need to do is *test if `stock is None`*. – Martijn Pieters Apr 03 '18 at 16:58
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [On topic](http://stackoverflow.com/help/on-topic) and [how to ask](http://stackoverflow.com/help/how-to-ask) apply here. StackOverflow is not a design, coding, research, or tutorial service. First, this is not how you check to see whether a variable is `None`; second, this is not how you catch an exception. – Prune Apr 03 '18 at 17:10

1 Answers1

-3

Try to enclose in try /except block:

try:
    if stock.find_all("option"):
        your other code
except Exception as e:
   print ("Error Happend")
Rehan Azher
  • 1,340
  • 1
  • 9
  • 17
  • 2
    Don't catch `Exception` unless you plan to re-raise it or to log the exception details. Otherwise you are just taping over coding errors. And there is zero need for that approach here. – Martijn Pieters Apr 03 '18 at 16:57
  • @MartijnPieters any other better approach Sir. OK i got it just check if stick is None. Am i correct? – Rehan Azher Apr 03 '18 at 16:58
  • Don't use bare exceptions. Basically, you're not taking advantage of the language to help you find problems. – Andre Araujo May 16 '21 at 04:47