Exception
Assert
  • assert() is defined in assert.h
  • The program will be terminated
  • #include <stdio.h>
    #include <assert.h>
     
    int main()
    {
    	int a = 10, b = 0;
     
    	assert (b != 0);
    
    	printf("End the program ...\n");
     
    	return 0;
    }
    		
    Exit
  • exit() is defined in stdlib.h
  • The program will be terminated
  • #include <stdio.h>
    #include <stdlib.h>
     
    int main()
    {
    	int a = 10, b = 0;
    
    	if(b == 0)
    	{
    		printf("Divided by zero ...\n");
    		exit(EXIT_FAILURE); // -1
    	}
     
    	printf("End the program ...\n");
     
    	return 0;
    }
    		
    Errno
  • 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;
    }