def set_attribute(attributes, name, value):
for i, attribute in enumerate(attributes):
if name in attribute:
quote_char = attribute.find('"')
if quote_char == -1:
raise ValueError
return None
attributes[i] = attribute[:quote_char+1] + str(value) + '"'
return attributes
I’m a new programmer and I’m trying to properly understand exception handling.
In this example every name should also have a " character in it somewhere, so I want to raise an exception if this fails, but I was also trying to understand if the return None statement is necessary (or does anything).
My understanding was that I would escape from each level of scope until an exception handler was found. The Python tutorial says this:
- First, the try clause (the statement(s) between the try and except keywords) is executed.
- If no exception occurs, the except clause is skipped and execution of the try statement is finished.
- If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named
after the except keyword, the except clause is executed, and then
execution continues after the try statement.- If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named
after the except keyword, the except clause is executed, and then
execution continues after the try statement.- If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no
handler is found, it is an unhandled exception and execution stops
with a message as shown above.
Yet, after reading this description, I’m realizing that I don’t understand exceptions, but I should.
So to state the question simply: is this return None statement necessary, and why? Also, where am I wrong about how exceptions work?
The
return Noneis junk. Python will never get there.You could simplify the code and run a little experiment to see if the value
FOOis ever returned:If
FOOwere returned, you might see it inprint(foo()), but indeed that line prints nothing. Instead you seeBad value.