How do I know all thrown exceptions of a function?
Delaney, Timothy
tdelaney at avaya.com
Mon Jan 22 18:33:55 EST 2001
> What about exceptions raised by dependent APIs? I mean, suppose for
> example that the exceptions raised by the file object, or the sys
> module, changes in Python 2.1; your API is now liable to raise a
> new exception thanks to those changes. Are you supposed to account
> for that as part of your API? In the same release, or later when
> you find out about it?
>
> I agree that an interface does include exceptions, but it isn't so
> clear how much can reasonably be specified. Exceptions generated
> in the immediate vicinity is one thing; "all thrown exceptions of
> a function" is another.
>
> ... to me exception handling feels like the most
> unfinished part of Python. Unfortunately I don't have any real
> ideas about it, I just find exception handling relatively error
> prone when it should be the opposite.
I agree here. Personally, I think Java's view of exceptions (almost) makes
sense.
Here is my take on things:
Four built-in exception classes, three of which form the basis for "trees"
of exceptions:
Exception
type(Exception) == <type 'Exception'>
used for "normal" exceptional circumstances - these
need to be declared
SilentException(Exception)
type(SilentException) == <type 'SilentException'>
used for things which should normally just pass
through (such as index-out-of-bounds) - these don't
need to be declared.
UndeclaredException(SilentException)
Raised when an undeclared Exception is
raised
Error
type(Error) == <type 'Error'>
used for "really bad" things which probably can't be
recovered - these don't need to be declared
A function needs to declare all the Exceptions it will raise. If a function
raises an Exception it doesn't declare, instead an UndeclaredException is
raised with the raised Exception as its data.
SilentException is a subclass of Exception so you can continue to do
try:
except Exception:
Things like index-out-of-bounds should be SilentException so they don't
explicity need to be declared in just about every function around.
There would be no requirement to catch any type of exception, whether
declared or not.
I think this covers all worries with backwards compatibility, whilst moving
towards a well-defined exception system.
Tim Delaney
Avaya Australia
More information about the Python-list
mailing list