need help on error handling.
Hi, I need some serious suggestions about error handling in C. Can some one please tell me of a better method to handle errors in my project. I will just post some code that I have written:
Code:
int init_plwave(void)
{
int flag = 0;
double theta, phi;
double freq;
double e0;
unsigned long nrays;
printf("Enter the number of rays\n");
if(scanf("%lu", &nrays) != 1)
{
fprintf(stderr, "Error while reading the number of rays\n");
flag = 1;
return flag;
}
printf("Enter the frequency of the rays\n");
if(scanf("%le", &freq) != 1)
{
fprintf(stderr, "Error while reading the frequency of the plane wave\n");
flag = 1;
return flag;
}
printf("Enter the direction(theta, phi) for the rays\n");
if(scanf("%lf %lf", &theta, &phi) != 2)
{
fprintf(stderr, "Error while reading the direction for the rays\n");
flag = 1;
return flag;
}
printf("Enter the source electric field\n");
if(scanf("%lf", &e0) != 1)
{
fprintf(stderr, "Error while reading the source electric field\n");
flag = 1;
return flag;
}
return flag;
}
int read_mesh(char *fname, mesh **m)
{
FILE *fp;
int flag = 0;
fp = fopen(fname, "r");
if(fp == NULL)
{
fprintf(stderr, "Error while opening file %s\n", fname);
flag = 1;
return flag;
}
*m = malloc(sizeof(mesh));
if(*m == NULL)
{
fprintf(stderr, "Couldn't allocate memory for the mesh\n");
flag = 1;
return flag;
}
if(parse_zeus_file(fp, m))
{
flag = 1;
return flag;
}
return flag;
}
Although, I do not feel there is anything wrong with this approach of checking for the error condition and then using fprintf to print errors, return some flag and terminate the function but as you can all see it is extremely verbose, repetitive and it looks as if there is hardly any code but only error handling in the program. Looks really ugly and gives a bad impression. I need some idea on a centralized error handling appraoch or atleast some suggestions on improving my technique. please help me.