I want to catch a specific ValueError, not just any ValueError.
I tried something like this:
try: maquina['WPF'] = macdat(ibus, id, 'WPF')
except: ValueError, 'For STRING = ’WPF’, this machine is not a wind machine.':
pass
But it raises a SyntaxError: can't assign to literal.
Then I tried:
try: maquina['WPF'] = macdat(ibus, id, 'WPF')
except ValueError, e:
if e != 'For STRING = ’WPF’, this machine is not a wind machine.':
raise ValueError, e
But it raises the exception, even if it is the one I want to avoid.
in
except ValueError,e,eis an instance of the exception, not a string. So when you test ifeis not equal to a particular string, that test is always False. Try:instead.
Example:
Typically, you don’t really want to rely on the error message if you can help it — It’s a little too fragile. If you have control over the callable
macdat, instead of raising aValueErrorinmacdat, you could raise a custom exception which inherits fromValueError:Then you can only catch
MyValueErrorand let otherValueErrors continue on their way to be caught by something else (or not). Simpleexcept ValueErrorwill still catch this type of exception as well so it should behave the same in other code which might also be catching ValueErrors from this function.