Which exceptions are recommended to me handled?
Delaney, Timothy (Tim)
tdelaney at avaya.com
Mon Jun 5 00:35:39 CEST 2006
Florencio Cano wrote:
> Is it recommended as a good programming practice to catch all
> exceptions and raise our own exceptions or let Python itself raise
> these kinds of exceptions?
> For example imagine a function that needs an integer and '34' is
> passed, this is ok because inside the function it uses int(variable)
> but if a 'hello' is passed it will raise a ValueError exception. Is
> it better to handle this exception or let Python raise directly
> ValueError and stop execution or what is recommended?
If you can validly handle the exception, do so. Otherwise, let it
propagate. Valid handling could be (for example) logging the error and
using a default value.
Note that it's a particularly bad idea to just replace one exception
with another exception (not suggesting that that is what you intended -
just something I've seen a lot ;)
raise MyValueError('Bad value: ' + val)
The most important problem here is that you've lost the stack trace from
the original exception. The next most important is that anything else
that believes it can handle a ValueError now won't be able to.
More information about the Python-list