How can we handle exceptions and errors in C like C++ and Java we use try {}
and catch{}
? Is there any way in C?
No, you can't but there are some patterns using goto (Goto is not always evil).
Example taken from this site
int foo(int bar)
{
int return_value = 0;
allocate_resources_1();
if (!do_something(bar))
goto error_1;
allocate_resources_2();
if (!init_stuff(bar))
goto error_2;
allocate_resources_3();
if (!prepare_stuff(bar))
goto error_3;
return_value = do_the_thing(bar);
error_3:
cleanup_3();
error_2:
cleanup_2();
error_1:
cleanup_1();
return return_value;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With