-2

I'm trying to grasp my head around try/except. Please see code below....

status = raw_input('What is your status?')


#if x is anything other othan "citizen", "legal", or "illegal" raise a ValueError


try:
    status == "citizen" or status == "legal" or status == "illegal"
except:
    raise ValueError

So, I want to raise a ValueError if the user inputs anything other than what is specified, which doesn't happen. I know I can just use an If statement and raise a ValueError that way. But why would this not work also. Should the code not jump the except block if anything within the Try block is False?

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
MJ_49
  • 21
  • 1
  • 3

1 Answers1

2

No, it shouldn't. The question of try is not whether a condition evaluates to true; it's whether the block of statements raises an exception. Your "status ==" expression will not raise an exception, so the "except" block won't be executed.

status = "other"

try:
    status == "citizen" or status == "legal" or status == "illegal"
except:
    raise ValueError

print "finished nicely"

Output:

finished nicely

Whereas this does give us an exception:

status = "other"
option_dict = {
    "citizen": 1,
    "legal": 2,
    "illegal": 3
}

try:
    option = option_dict[status]
except:
    raise ValueError

print "finished nicely"

Output:

Traceback (most recent call last):
  File "/home/wdwickar/QA_Test/testcases/so.py", line 11, in <module>
    raise ValueError
ValueError

Without the try-except block, we get

KeyError: 'other'
Prune
  • 76,765
  • 14
  • 60
  • 81