- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Error Handling in C
Error handling is not supported by C language. There are some other ways by which error handling can be done in C language. The header file “error.h” is used to print the errors using return statement function.
It returns -1 or NULL in case of any error and errno variable is set with the error code. Whenever a function is called in C language, errno variable is associated with it. errno is a global variable and is used to find the type of error in the execution.
The following table displays some errors −
Sr.No | Errors & Error value |
---|---|
1 | I/O Error 5 |
2 | No such file or directory 2 |
3 | Argument list too long 7 |
4 | Out of memory 12 |
5 | Permission denied 13 |
There are some methods to handle errors in C language −
perror() − This function is used to print the error and it returns the string along with the textual representation of current errno value.
strerror() − This function is declared in “string.h” header file and it returns the pointer to the string of current errno value.
Exit status − There are two constants EXIT_SUCCESS and EXIT_FAILURE which can be used in function exit() to inform the calling function about the error.
Divided by zero − This is a situation in which nothing can be done to handle this error in C language. Avoid this error and you can check the divisor value by using ‘if’ condition in the program.
Here is an example of error handling in C language,
Example
#include <stdio.h> #include <stdlib.h> main() { int x = 28; int y = 8; int z; if( y == 0) { fprintf(stderr, "Division by zero!\n"); exit(EXIT_FAILURE); } z = x / y; fprintf(stderr, "Value of z : %d\n", z ); exit(EXIT_SUCCESS); }
Output
Here is the output
Value of z : 3