Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we handle errors and exceptions in c like other languages(c++ and Java)?

How can we handle exceptions and errors in C like C++ and Java we use try {} and catch{}? Is there any way in C?

like image 301
user2809576 Avatar asked Oct 02 '13 07:10

user2809576


1 Answers

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;
}
like image 102
Arnaud Denoyelle Avatar answered Oct 12 '22 02:10

Arnaud Denoyelle