The Right Approach to Exceptions

Robert Jacques sandford at jhu.edu
Sun Feb 19 09:13:46 PST 2012


On Sun, 19 Feb 2012 01:07:44 -0600, Jonathan M Davis <jmdavisProg at gmx.com> wrote:

> 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
> many cases.
>
> 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
>

Most of Phobos is an internal library. I think parsing routines are a bad counter-example to my point; combined validation and conversion is generally part of their mandate and we expect them to fail often. We also don't expect the parsing of user input to live deep inside code base; it's almost always done as close to the input as possible (i.e. in the input text box). All too often you end up with code like: try{ parse(...); } catch {...} Also, although less of a problem in D, not ensuring that in input string actually is a string was the source of many a C exploits.


More information about the Digitalmars-d mailing list