280 likes | 1.2k Views
Error Handling in C. Errors - An unpleasant way. Errors – Graceful degradation of service. Error Handling. There are always some errors in programs/software It’s a programmers job to anticipate errors And make the program to handle errors gracefully.
E N D
Error Handling • There are always some errors in programs/software • It’s a programmers job to anticipate errors • And make the program to handle errors gracefully. • Users cannot understand technical jargons • A message from the program must inform the user that something unexpected occurred • Which will be taken care of in due course of time
Error Handling in C • Modern programming languages provide support for error handling (sometimes called exception handling) • C however, provides limited error handling in the form of returned values • Most of the times, if a function returns NULL or the value -1, it means that an error has occurred • In DevC++, error codes defined for various operations are defined in errno.h
Error Handling in C • We have already implemented (in one of the ways) the capability of handling errors in our programs • Remember…??? if (inputfp == NULL) { printf("Can't open input file my_input.txt!\n"); system("pause"); return 0; } • Lets try another way of handling similar errors
Error Handling in C • The function perror() prints out the string strfollowed by the actual string equivalent of the error that had occurred if (inputfp== NULL) { perror("Error printed by perror"); } • The output of this code segment would be: Error printed by perror : No such file or directory
Error Handling in C • We can make similar arrangements for other errors such as: • Divide by zero • Unsuccessful memory allocation operation with malloc().