How to find where error is
How can I find where the error occurs? In C language, the return value means what error occurs, such as failure to open file or memory allocation. There is no information where the error occurs.
For example, function 'foo' calls A,B,C,D. If foo returns an error value, it might be return value of A or B or C or D. I cannot 开发者_开发问答find what function returns error. I have to run debugger or add some codes to find what function returns error.
Yes, you'll have to use a debugger or add extra code to display some output. Also, make sure you look at the pre-conditions for the function you call (if there are any) - make sure that you obey what it demands before calling it.
I think you've answered your question, you need to use a debugger to find out. Maybe add some breakpoint, look if the error occurs always or only sometimes, and in the same place.
C library functions like fopen()
set errno
to give you a bit more diagnostic information. You could use a similar strategy. But if you don't program in some way of getting extra information out like that, you are stuck with the debugger.
Design an appropriate error handling that provides the informations you need. Then write your functions around this design. Using the return values is just one of many possibilities to do this, but obviously not enough for your specific requirements.
What error occurs is a clue for where it occurs: if A can return only error #5, B only #42, C only #3 and D only #56, whenever foo returns #5, you know that it comes from A.
If error codes overlap over different functions, you can get other clues from your inputs and your outputs: if D either displays a message or issues an error #5, whenever foo returns #5 and the message gets displayed, you know that error comes from A.
If error code, inputs and output are not enough to retrieve error location, you have to increase observability of your program. Some solutions are:
- add debug info and use a debugger
- add logs that you can activate or inhibit at will
- select unique error codes so that what error occurs identifies where it occurs as well
精彩评论