More exception classes into Phobos?

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Thu Mar 23 17:50:50 PDT 2017


On Thu, Mar 23, 2017 at 05:28:16PM -0700, Walter Bright via Digitalmars-d wrote:
> On 3/23/2017 1:45 PM, Adam D. Ruppe wrote:
> > I'm of the firm belief that exceptions should NEVER have a string
> > message - that's a code smell. If you do it right, all the info can
> > be determined automatically by the exception type and passed
> > arguments and *that* is what gets printed to string.
> 
> The string is what gets printed to the user like:
> 
>    "your password has to have at least one upper case character in it"
> 
> In general, such is not deducible from the type/arguments.
[...]

You *could*, in theory, create very fine-grained exception types like:

	class PasswordInsufficientCharSetException {
		string category; // like "uppercase letters"
		int quorum;
	}

	class PasswordMinLengthException {
		int minLength;
	}

	try { checkPassword(pw); }
	catch(PasswordInsufficientCharSetException e) {
		writeln("Your password must have at least %d characters from the category %s",
			e.quorum, e.category);
	}
	catch(PasswordMinLengthException e) {
		writeln("Your password must be at least %d characters long", e.minLength);
	}
	catch( /* other fine-grained types */ ) { ... }

The problem with this, though, is that every such fine-grained exception
type becomes part of the tight coupling between the throwing code and
the catching code, to the point that you end up essentially forcing the
catching code (usually user code if the exception is thrown from a
library) to implement what you could have already implemented in a much
easier way in the throwing code instead.

Essentially, having exceptions of this level of detail forces the
catching code to be dependent on the implementation details of the
throwing code (it has to know which set of exceptions can be thrown, and
it has to know the details of the exceptions it'd like to catch, what
each detail means, and what to do with it), which breaks encapsulation
and is what I'd call the *real* code smell.

It's a different story, of course, if the library provides a
getErrorMessage(Exception e) function that hides these details away from
the catching code's eyes. But in that case you might as well just
include the error message in the original exception in the first place.


T

-- 
People tell me I'm stubborn, but I refuse to accept it!


More information about the Digitalmars-d mailing list