The Right Approach to Exceptions
acehreli at yahoo.com
Tue Feb 21 14:29:25 PST 2012
On 02/18/2012 09:09 PM, Jim Hewes wrote:
> I think of exception handling as tied to contract programming.
I think your use of the word 'contract' is colliding with the contract
programming feature. What you describe later does not match with the
contract programming and I guess is the reason why Andrei is pointing
out two chapters from TDPL.
I will reread those chapters later today but I think Andrei is referring
to the distinction between assert() and std.exception.enforce().
> function has a specific job that it's supposed to do. If for any reason
> it cannot do that job successfully, an exception should be thrown.
Agreed. That is how we have been using exceptions in C++ successfully at
where I work. It makes everything simple.
> can include even bad parameters
Yes, enforce() in D is great for that. I think Andrei agrees.
> (although if you have bad parameters to
> internal functions I'd think that is a design bug and could be handled
> by asserts).
Yes. Contract programming uses asserts().
> If what you mean is that exceptions should not be used to return
> information when the function is successful, I agree. But it can be used
> to return extra details about errors when a function fails.
Agreed. Again, this is how we have been using exceptions. We have the
equivalents of detailed exception types that Jonathan M Davis has been
mentioning. Come to think of it, less than a dozen.
> Not every
> exception coming out of a function was generated by that function. It
> may have come from several levels below that.
Of course. It is very useful.
> Maybe you can handle the
> former because it is more immediate but not the latter. So without
> exception types how would you know the difference between them? You
> could use error codes and switch on them but it defeats one of the main
> purposes of exception handling. So I think if there are exceptions
> generated from further away, it's an argument _for_ exception types
> rather than against it.
> For example, just have one BadParameter exception and then store
> information about which parameter is bad and why in the exception.
I would like to add that exceptions are thrown by code that doesn't know
how the exception will be useful. For that reason, especially a library
function must provide as much information as possible. Going with the
same examples in this thread, FileException is not a good exception to
throw when the actual problem is a FilePermissionException or a
More information about the Digitalmars-d