errno is a global macro shared by the functions in a program, defined in errno.h
perror(), attach errno message to the parameter string, defined in stdio.h
strerror(), create a string containing the errno message, defined in string.h
Not termnate the program
#include <stdio.h>
#include <errno.h>
#include <string.h>
extern int errno;
int main()
{
FILE *f = fopen("unknown.txt", "r");
if(f == NULL)
{
perror("Errno");
fprintf(stderr, "Error: %s\n", strerror(errno));
}
else
fclose(f);
printf("End the program ...\n");
return 0;
}
Try ... Catch
setjmp(buf), initial the buf, return 0
longjmp(buf, value), return an integer value, and jump to the location of setjmp(buf) and re-run setjmp(buf)
#include <stdio.h>
#include <setjmp.h>
static jmp_buf buf;
int divide(int a, int b)
{
if(b == 0)
longjmp(buf, 1); // throw
return a/b;
}
int main()
{
int a = 10;
for(int b = -5; b <= 5; b++)
{
if(!setjmp(buf)) // try
printf("%d\n", divide(a, b));
else // catch
printf("Divided by zero ...\n");
}
return 0;
}