[Tutor] Impossible Else as Exception
Alan Gauld
alan.gauld at btinternet.com
Wed Apr 10 01:14:12 CEST 2013
On 09/04/13 20:22, Jordan wrote:
> I want to know what exception should be raised if there is a bug in my
> code that allows an else statement to be triggered, because the else
> condition in my code should be impossible,
class BuggyCodeError(StandardError): pass
Maybe?
Seriously, exceptions are not intended for handling buggy code.
You should be removing the bugs using assertions and tests.
The exception to raise is whatever is appropriate to how you
got into that else and that depends on the nature of the
conditions.
One option might be a ValueError or maybe an IOError.
I'm not sure I agree with the suggestion to use AssertionError because
that implies it came from an assertion. I'd rather define a bespoke
error class than use that.
> if condition is 1:
> do something with 1
> elif condition is 2:
> do something with 2
> else: # Impossible unless the code above is flawed.
> Raise Exception
If its really impossible for the condition to be anything other than 1
or 2 then an elif should not be needed. If it is possible to get another
value think about what causes could exist to get the
other value ( even if it is a code error!!) and describe the cause(s).
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list