In languages and/or libraries which do not support exceptions, many/almost all functions return a value indicating success or failure of their operation - the best-known example being perhaps UN*X system calls such as open()
or chdir()
, or some libc functions.
Anyway, when I write C code, it very often ends up looking like this:
int retval;
...
retval = my_function(arg1, arg2);
if (retval != SUCCESS_VALUE) { do_something(); }
retval = my_other_function(arg1, arg2);
if (retval != SUCCESS_VALUE) { do_something_else(); }
Now, what I would like is to just not save the retval anywhere and have errors thrown in exceptions, but I can't have that. What's the next best thing? I know that there's no real solution to this problem, but I would still like to do something.
Some ideas:
assert()
's (but that's not for production code which can't afford to just die).ensure_success(my_function(args)
or ensure_success(my_other_function(args),my_error_handler,error_handler_args)
.Is there any other practice in this matter I might prefer?
Edit:
Try to approach this problem with a sort of scientific curiosity. There are many that claim that C's approach to error handling leads to programmers being more aware of error conditions, paying more attention to errors and where/how they should be treated. Just consider this an exercise (if a bit tedious) of awareness, like meditation :)
Don't fight it. Solve this as much as possible in the spirit of C and your view of things will expand slightly.
Check out this article on C error handling mantra: http://tratt.net/laurie/tech_articles/articles/how_can_c_programs_be_so_reliable
One general answer to your general question is: try to make functions as small as possible so that you can directly return from them on errors. This approach is good in all languages. The rest is an exercise in structuring code.