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

ShadoLight ettienne.gilbert at gmail.com
Fri Feb 25 10:37:55 UTC 2022


On Thursday, 24 February 2022 at 20:01:20 UTC, H. S. Teoh wrote:
>
> The problem with replacing exceptions with return codes is that 
> it requires writing tons of boilerplate to handle error codes. 
> I work with C at work every day, and eventually every function 
> starts looking like this:
>
> 	int some_func(some_type_t *some_args) {
> 		int ret = SOME_FUNC_ERR;
>
> 		if ((ret = do_something(...)) != DO_SOMETHING_OK)
> 			goto EXIT;
>
> 		if ((ret = do_something_else(...)) != DO_SOMETHING_ELSE_OK)
> 			goto EXIT;
>
> 		if ((ret = do_yet_another(...)) != DO_YET_ANOTHER_OK)
> 			goto EXIT;
>
> 		// ... ad nauseaum
>
> 		ret = SOME_FUNC_OK;
> 	EXIT:
> 		return ret;
> 	}
>
> Every single function call must be wrapped with `if ((ret = 
> blah(bleh)) == bluh)` boilerplate,...etc..

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:

int some_func(some_type_t *some_args) {
	int ret = SOME_FUNC_ERR;

	if ((ret = do_something(...)) != DO_SOMETHING_OK)
		goto EXIT;

	if ((ret = do_something_else(...)) != DO_SOMETHING_ELSE_OK)
		goto EXIT;

	if ((ret = do_yet_another(...)) != DO_YET_ANOTHER_OK)
		goto EXIT;

	// ... ad nauseaum

	ret = SOME_FUNC_OK;
EXIT:
	// ...some cleanup here

	return ret;
}

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.


More information about the Digitalmars-d mailing list