Home > Back-end >  C try/except without additional modules
C try/except without additional modules

Time:12-07

I have a C code and I want to print a String if any error has occured during runtime. in python it will be an easy try.. excpet.. condition. is there a way to do the same in C, without using additional modules?

CodePudding user response:

Note: Sorry for my bad english
C doesn't have any concept of exceptions, C does but thats beside the point of your question.

In C we use different methods to check errors:

  1. Mixed return value:
    • The function that failed returns a special value. E.G malloc returns NULL on failure
    • The function that failed returns a value that doesn't match the case. E.G a function that does something on an array and returns the number of array elements that it has done the job on, you gave it an array of 5 elements it returned 3, definitely there is a problem.
  2. Dedicated return value
    • If the function doesn't have something to return but is subject to failure, it can return true/false or a number indicating the state
    • If the function has something to return, it takes a pointer parameter, puts the data in the pointer address, returns true/false or a number inidicating the state.
  3. Global error holder
    • The function puts a value that indicates an error in a global error variable
    • The function appends the error to a global array of errors.
  4. Signals (thanks to @thebusybee)
    • You set an error handler beforehand, then call the function, that function signals your error handler
    • An error handler is passed directly to the function instead of setting it beforehand (in practice this is not a thing that a C programmer would do since there is no standard for lambdas in C it becomes quite a mess, also why pass the handler everytime when you can set it one time)

Note: AFAIK signals doesn't have to be asynchronous

CodePudding user response:

Not totally sure what you are trying to do, but C has an atexit function that you could use to try to dump some error to stderr. It is a callback you register with the system but could give access to your error string.

  • Related