Is this a correct way to generate an exception when getting a wrong parameter

Chris Angelico rosuav at
Wed Aug 12 11:25:56 CEST 2015

On Wed, Aug 12, 2015 at 7:06 PM, Cecil Westerhof <Cecil at> wrote:
> I have:
> ========================================================================
> accepted_params     = {
>     'pcpu',
>     'rss',
>     'size',
>     'time',
>     'vsize',
> }
> ========================================================================
> Later I use:
> ========================================================================
> if (to_check != 'all') and not(to_check in accepted_params):
>     raise Exception('Used illegal parameter: {0}.\n'
>                     'Accepted ones: {1}'
>                     .format(to_check, sorted(accepted_params)))
> ========================================================================
> When using 'all' I want to do the work for all accepted parameters.
> ;-)
> Is this a correct way to do this, or is there a better way?

There are a couple of things I'd do slightly differently, one of which
is to raise ValueError rather than Exception; but mostly, yes, that
seems reasonable. I'd also use "x not in y" rather than "not (x in
y)", for obvious reasons of clarity. But it kinda depends on what
those params are going to be used for. Maybe you don't need to check
at all - maybe something elsewhere will have a table that maps a
parameter to something else, and absence from that table is a clear
indication that it's an invalid parameter. If at all possible, have a
Single Source Of Truth (SSOT), from which everything else derives.


More information about the Python-list mailing list