Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason why perror isn't widely seen in code for error handling? [closed]

Looking at code at stackoverflow or elsewhere, it seems I rarely see perror() being used to report the exact nature of an error. printf is much more common. Is this an indicator that there's something wrong or missing with perror? I'd expect it to be used much more often given that it gives better information.

like image 254
Gustavo Litovsky Avatar asked Jan 23 '13 16:01

Gustavo Litovsky


2 Answers

I personally prefer strerror() which does roughly the same thing, but allows you to use the error message together with a printf or similar function that gives further useful [to the coder or user of the program, depending on the type of error].

For example:

errno = 0;
FILE *f = fopen(argv[1], "rb");
if (!f)
{
    fprintf(stderr, "File %s open failed: error code %d ('%s')\n", 
            argv[1], errno, strerror(errno));
    exit(1);
}

That way, we also know WHICH file (say it's a program that copies a file, perror wouldn't necessarily tell you if it was the "source" or "destionation").

If the error is for programming errors [or "stuff that aren't expected to go wrong"], you can also do something like this:

#define UNEXPECTED(cond) do { if (cond) { do_unexpected(errno, #cond, __FILE__, __LINE__); } while(0)

void do_unexpected(int err, const char* cond, const char *file, int line)
{
    fprintf(stderr, "Unexpected error %s [errno=%d, errstr=%s] at %s:%d", 
            cond, err, strerror(errno), file, line);
    exit(1);
}

errno = 0;
FILE *config = fopen("config.txt", "r");

UNEXPECTED(!config); 

... 

That's assuming you don't expect the "config.txt" to be removed, as an example [that's pretty bad programming in general, but perhaps there is a valid reason for it...]

like image 180
Mats Petersson Avatar answered Sep 19 '22 23:09

Mats Petersson


perror() wont exactly give you the line number where error happened, while your printf() would help you identify the exact line where it is being printed. So I think it as more helpful in debugging, nothing wrong with perror() that I know of ....

like image 34
Jagdeep Sidhu Avatar answered Sep 20 '22 23:09

Jagdeep Sidhu