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

- 4,333
- 15
- 39
- 33

- 121
- 1
- 2
- 11
-
11Since there are no exceptions in C, there's no need to handle them! – Kerrek SB Oct 02 '13 at 07:38
-
1By the way, [think twice before using exceptions](http://stackoverflow.com/q/1744070/912144). – Shahbaz Oct 02 '13 at 11:25
-
Please follow this link below:: [Exception Handling in C without C++](http://www.on-time.com/ddj0011.htm) Thank you – vkulkarni Oct 02 '13 at 07:45
2 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;
}

- 29,980
- 16
- 92
- 148
-
On the plus side, once you embrace this logic, you appreciate all the work a C++ compiler has to do every day :-) – Kerrek SB Oct 02 '13 at 07:45
-
@KerrekSB and at the same time depreciate the non-existing error handling in most C++ applications. :( – Shahbaz Oct 02 '13 at 11:24
-
1until 2 weeks ago, I was convinced that using `goto` was a sin. Then someone on StackOverflow showed me how to handle errors with it... – Arnaud Denoyelle Oct 02 '13 at 12:11
-
@ArnaudDenoyelle, error handling without `goto` (in C) requires either a huge amount of nested `if`s, or a huge amount of cleanup duplication (depending on whether the `if`s are on whether operation succeeded or failed). They are the cleanest most intuitive way of error handling (again, in C). – Shahbaz Oct 02 '13 at 13:58
Is there any way in C?
You dont do exception handling in C.
Just had this C Language Exception Handling as a work around I would say.
Typically C (as any old language) do manage such situation with error code returned, possible errno setted and a table of string that explain errno (
sys_errlist
). Thus a typical error management in C require to test any error on functions that may returns error (almost all standard libc functions) and, if error occur, manage it some way.
setjmp()
andlongjmp()
functionsThis article will describe what should/could be done in a exceptional _C_ase. C language miss exception handling support and runtime, does not exists things like C++'s
try
..catch
, does not exist exception class definition and hierarchy, but there are nice functions likesetjmp()
andlongjmp()
that behave someway as try catch#include <setjmp.h> #include <stdio.h> int foo(int p) { if (p) siglongjmp(env,p); /* return to sigstejmp returning p */ return 0; } static sigjmp_buf env; int main() { int a,r; if (!(r=sigsetjmp(env, 1))) { for (a=0; a<10; a++) { fprintf(stdout,"%d\n",foo(a)); fflush(stdout); } } else { fprintf(stdout,"exceptionally returned %d",r); fflush(stdout); } }
sigsetjmp and siglongjmp are variant conforming to posix and compatible with bsd standard (see GNU Libc documentation)
... yes, it look like try{..}catch(..) in C++ except for the missing catch argument, and that there is only one level of exception
Error Handling in C:
C does not provide direct support for error handling (also known as exception handling). By convention, the programmer is expected to prevent errors from occurring in the first place, and test return values from functions.
There is an external variable called "errno", accessible by the programs after including
<errno.h>
- that file comes from the definition of the possible errors that can occur in some Operating Systems

- 168,305
- 31
- 280
- 331
-
2technically you can use a stack to nest exceptions and use the return value for an exception type to test for and if not to be handled just pop off the stack and siglongjump again. either way it's clunky – ratchet freak Oct 02 '13 at 08:15
-
@ratchetfreak:- Rightly said.!+1 The link which I have shared has that **An exception stack implementation** as well. – Rahul Tripathi Oct 02 '13 at 08:18
-
Not sure how many people will be happy with this sort of trickery in production code. – Nobilis Oct 02 '13 at 08:18
-
1@Nobilis:- Yes I agree but I think before that how many people would use **C for exception handling** and thats why I referred it as work around ;) – Rahul Tripathi Oct 02 '13 at 08:19
-
Note that with that approach you don't get resource freeing like with C++ destructors (nor you have it with errnos, so there is no benefit nor drawback here). Problems though start when you enable optimization of generated code as some variables you might expect to have changed after longjmp might be reverted to values before setjmp as they were only in registers. In your example you can't rely on `a` having initialized value when you enable optimizations (at least under gcc). – elmo Oct 02 '13 at 10:02
-
@elmo, doesn't `setjmp` push all registers and recover them after the jump? It's highly unlikely that they didn't think of that. Even without optimization, you always have some stuff in your registers you wouldn't want destroyed. – Shahbaz Oct 02 '13 at 11:34
-
Isn't setjmp and longjmp a good name for `goto`????? http://stackoverflow.com/questions/18518632/why-and-when-should-a-goto-be-used-in-c-c – woliveirajr Oct 02 '13 at 11:57
-
@Shahbaz: it does, that's exactly why there is issue in optimized code. Variable gets some value assigned (or not, look at `a` above, it gets random value), `setjmp` is called which stores variable value as part of register values, then you modify variable and call `longjmp`. Call to `longjmp` now restores initial value (from just before call to `setjmp`). In above example if you wanted to print which iteration it was you would: most probably get correct if no optimization was enabled, got garbage/uninitialized value with O2 and above. – elmo Oct 02 '13 at 12:08
-
@Shahbaz:- May be I am missing the context but just read that setjmp()/longjmp() are not meant to save the stack. setjmp.h is a header defined in the C standard library to provide "non-local jumps": control flow that deviates from the usual subroutine call and return sequence. The complementary functions setjmp and longjmp provide this functionality. – Rahul Tripathi Oct 02 '13 at 12:18
-
Also read this article on the same:- http://web.eecs.utk.edu/~huangj/cs360/360/notes/Setjmp/lecture.html Am i missing the obvious? – Rahul Tripathi Oct 02 '13 at 12:20
-
RahulTripathi, `setjmp` _is_ supposed to save the stack. See [the man page](http://linux.die.net/man/3/setjmp). @elmo, I'm not sure why you say `a` changes after the `longjmp` above, but even in a situation that it does, then I think it falls under the case of "value of `a` not persistent", which means it should have been `volatile`. – Shahbaz Oct 02 '13 at 13:55
-
@elmo, what I mean is, if `setjmp`/`longjmp` simply broke code due to any kind of optimization, they would be so outright dangerous that they would in the very least be deprecated. But they are not. – Shahbaz Oct 02 '13 at 13:56
-
@Shahbaz:- Got your point Sir! Many interesting points you have left in comments. If that would have been in some answers I would have upvoted for you :) – Rahul Tripathi Oct 02 '13 at 13:57
-
@Shahbaz: I didn't say they are breaking code. It works as it is defined. I only pointed out it might not be what you want/expect. `setjmp` and `longjmp` fall outside C specification and I think POSIX is somewhat flexible on implementations, so optimizations might impact what will happen as none of the standards imposes any restrictions. – elmo Oct 02 '13 at 15:05