The Right Approach to Exceptions
Jonathan M Davis
jmdavisProg at gmx.com
Sat Feb 18 23:07:44 PST 2012
On Sunday, February 19, 2012 00:21:38 Robert Jacques wrote:
> Not to jump on you in particular :) but bad user parameters should never be
> treated as exceptional. Even bad 'internal' parameters that are passed via
> the external API aren't exceptional. Programmers being lazy about input
> parameter checking is how hackers make their money.
I completely disagree. I think that there are many cases where throwing an
exception on bad parameters is exactly what you should do. Phobos does this in
many places. Often, the function knows best what it wants, and it's the best
position to check it. So, having it check the input makes a _lot_ of sense in
For instance, take fromISOExtString on std.datetime.SysTime. Is it at all
reasonably to expect that the caller is going to verify that the string is
well-formed according to the ISO standard? No. And it's highly probable tha
the string being given came from I/O of some kind - be it a file or a socket or
whatever. So, it makes _way_ more sense for fromISOExtString to check the
string itself and throw on failure. It's also more efficient to do that, because
if you checked that the string was valid before passing it to
fromISOExtString, then you'd be processing the string twice.
There are other cases where you want to use DbC and require that a function is
given valid arguments. In those cases, you use assertions, so the checks go
away in release mode. But that's not always the best way to go about. And in
defensive programming, you end up checking exceptions quite heavily - even in
release mode - and throwing when they're bad.
The best approach depends on what you're doing, and what the functions are
used for. But approaches have their place.
- Jonathan M Davis
More information about the Digitalmars-d