Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception handling in pure C [duplicate]

Possible Duplicate:
C : How do you simulate an 'exception' ?

Hi, I know that exception handling is available in C++ but not in C. But I also read that exception handling is provided from OS side, so isnt there any function for C invoking the same behavior from OS as try catch and throw? Thanks.

like image 783
B.Gen.Jack.O.Neill Avatar asked Oct 19 '10 15:10

B.Gen.Jack.O.Neill


People also ask

Is there any exception handling in C?

The C programming language does not support exception handling nor error handling. It is an additional feature offered by C. In spite of the absence of this feature, there are certain ways to implement error handling in C. Generally, in case of an error, most of the functions either return a null value or -1.

How does C handle errors?

As such, C programming does not provide direct support for error handling but being a system programming language, it provides you access at lower level in the form of return values. Most of the C or even Unix function calls return -1 or NULL in case of any error and set an error code errno.

Which code structure is the standard for exception handling?

try-catch – We use the try-catch block for exception handling in our code. try is the start of the block and catch is at the end of the try block to handle the exceptions. We can have multiple catch blocks with a try block. The try-catch block can be nested too.


3 Answers

The C language itself has no support for exception handling. However a means of exception handling for C does exist on a platform + compiler specific basis.

In windows for example C programs can use SEH exception handling.

  • http://www.microsoft.com/msj/0197/Exception/Exception.aspx

I've seen arguments in the past that the C function pair setjmp and longjmp is exception handling in C. I consider it closer to the ejection pattern but it's worth investigating

  • http://msdn.microsoft.com/en-us/library/aa272905(VS.60).aspx
like image 144
JaredPar Avatar answered Oct 23 '22 23:10

JaredPar


Not in a platform-independent way. And this would only be for hardware/OS-level exceptions, not SW exceptions.

like image 33
Oliver Charlesworth Avatar answered Oct 23 '22 23:10

Oliver Charlesworth


C provides exceptions in a standard library: setjmp()/longjmp().

like image 2
Joshua Avatar answered Oct 23 '22 22:10

Joshua