[OT] - C++ exceptions are becoming more and more problematic

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Feb 25 16:47:37 UTC 2022


On Fri, Feb 25, 2022 at 10:37:55AM +0000, ShadoLight via Digitalmars-d wrote:
[...]
> Not a comment about your point in general but, yeah, even though I
> agree with your point, in this specific example, you could have
> avoided all the gotos:
> 
> int some_func(some_type_t *some_args) {
> 	int ret = SOME_FUNC_ERR;
> 
> 	if ((ret = do_something(...)) != DO_SOMETHING_OK)
> 		return SOME_FUNC_ERR;
> 
> 	if ((ret = do_something_else(...)) != DO_SOMETHING_ELSE_OK)
> 		return SOME_FUNC_ERR;
> 
> 	if ((ret = do_yet_another(...)) != DO_YET_ANOTHER_OK)
> 		return SOME_FUNC_ERR;
> 
> 
> 	// ... ad nauseaum
> 
> 	return SOME_FUNC_OK;
> }
> 
> But, where I have found it unavoidable (in C) to use this 'goto' style
> (and which - I'm certain - is where your example originates from) is
> when you have some common cleanup to do at the end:

Yes, I omitted the cleanups, but yeah that's where the goto's come from.
The thing is, sooner or later you're gonna hafta add cleanups. It seems
to be an inevitable fact of life as the function grows more hairs from
bugfixes, enhancements, and what-not.

And experience shows that it's better to just begin by writing the
fully-general form from the beginning than to add it later, because what
tends to happen is that some hapless guy comes along after the fact and
goes "oh right I need to cleanup" and then rewrites some of the return's
to gotos, but misses a few, thus introducing resource leak bugs.


[...]
> I have yet to find a way to avoid this in C. OTOH in C++/D/etc
> exceptions are just such a super convenient way to handle this case.
> In code where you are not concerned with the cost of exceptions or
> optimization I'll really miss them.

That's the thing about people with C/C++ mentality (myself included --
that's the background I come from). You find a case where a particular
construct is less than optimal, and then you decide to forego that
construct entirely, even where performance doesn't really matter and
that construct could have helped your code be cleaner and more
maintainable.

Exceptions seriously help a LOT with making cleaner APIs and in writing
code faster.  Where it becomes a hindrance to runtime performance,
`nothrow` is right there for you to use.


T

-- 
Real men don't take backups. They put their source on a public FTP-server and let the world mirror it. -- Linus Torvalds


More information about the Digitalmars-d mailing list