exception handling in c



What is Exception Handling?

Whenever we create any application/software in any language(Java,C,C++,Python etc) then there are chances of Runtime error which may occur even if the software is in production level,So such type issues  are known as runtime error or Exception,So it become essential to manage such type of error otherwise it will disturb the normal flow of software/application.

I will give one example from that you will get clear idea about it,Lets suppose we have created one Calculator Application  here we have integrated basics mathematics functions like Addition,Subtraction,Multiplication,Division.Here if user by mistakenly  performing division operation of any number with 0 then it will raise an Exception and program execution will stop since it is not possible to divide any error with zero So to manage  this type of issues we need to use Exception Handling concept.


Some of the most common Exception are as follow:

FileNotFoundException

DividebyZeroError

NullPointerExcption

MemoryError


 Till the date,C Programming does not provide the exception handling or error handling directly but we can achieve it using one of the header file(errorno.h) provided by C.errorno.h header file contains all  runtime error which may occur during the execution of c program and it has unique errorno associated with it.

In order to give the error message to user,A Developer has to prevent error at first place and return values from the function.Most of the C Function calls return -1 or NULL in case of an error

Following are Some of the common error and its description :

errno value       Error

1             /* Operation not performed */

2             /* No such file or directory */

3             /* No such process */

4             /* Interrupted system call */

5             /* Input/Output error */

6             /* No such device or address */

7             /* Argument list too long */

8             /* Execution format error */

9             /* Bad file number */

10            /* No child processes */

11            /* Try again */

12            /* Out of memory */

13            /* Permission denied */


Moving ahead,we will first the program on see how error values are set if program found any error during it's execution.

main.c 

#include <stdio.h>
#include<errno.h>
int main()
{
    FILE * f;
    f = fopen("inspiredcoder.txt", "r");
  
    printf(" Value of Error Number: %d\n ", errno);
  
    return 0;
}


Output-Value of Error Number: 2

In above program,the error value is 2 because In my current directory where my main.c resides there was no file of name inspiredcoder.txt and we already saw in the errono's table  "No such file or directory" message is associated with error number 2.Some online compiler will give error no-13  which says permission denied.One important to note here is that errno is a keyword which is used to show error messages.

In-built methods which will help us to achieve Exception handling 
As of now we are only able to identify the error number what if we want to show error message's accordingly.To overcome this issue we have 2 method's they resides in errno.h header file,they are perror() and strerror().

perror():This function display the string you pass to it,followed by a colon,a space and then the textual representation of the current error value. 

strerror():this function returns a pointer to the textual representation of the current errno value.

Syntax  of perror() Function:

void perror(const char *string)
string:We can pass any custom message which we want to print before the error message itself,

Syntax  of strerror() Function:

char *strerror (int errnum)
errnum: is the error number (errno).

C Program to see how sterror() and perror() message are used to print the error messages 

// Online C compiler to run C program online
#include <stdio.h>
#include <errno.h>
#include <string.h>
  
int main ()
{
    FILE *f;

    f = fopen(" inspiredcoder.txt ", "r");
      printf("The error message is : %s\n", strerror(errno));
    perror("Message from perror");
    
  
    return 0;
}

Output-The error message is : No such file or directory
             Message from perror: No such file or directory


In above program,we have used strerror() in which we are passing errorno as a parameter which will help strerror() to show error message accordingly.In the next line we are perror message which will print the error message automatically which just need to pass any custom message before the error message,In above example we have passed  'Message from perror' as custom error message.

Exit Status:C standard Specifies two standard constants they are EXIT_SUCCESS and EXIT_FAILURE,they combinly can  be used to achieve catch or except block(Like we used to do in Python or Java),Since till now we are only able to recognize error and print it,but now we have to make sure once error is encountered then we have to manage the remaining flow of the program,So to do it we are going to use EXIT_FAILURE and EXIT_SUCCESS constants,these are macros defined in stdlib.h
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
  
int main ()
{
    FILE * f;
    f = fopen ("filedoesnotexist.txt", "rb");
  
    if (f == NULL)
    {
        printf("Value of Error Number: %d\n", errno);
        printf("Error while opening the file: %s\n",
                             strerror(errno));
        perror("Error printed by perror function");
  
        exit(EXIT_FAILURE);
        printf("I am not going to be printed\n");
    }
  
    else
    {
        fclose (f);
        exit(EXIT_SUCCESS);
        printf("I will not be Printed\n");
    }
    return 0;
}
Output-Value of Error Number: 2
Error while opening the file: No such file or directory
Error printed by perror function: No such file or directory

In above program we can see that we have used EXIT_FAILURE and EXIT_SUCCESS Constants,from above program we get to known that we have to use EXIT_FAILURE constants  when we have encountered the error and want to proceed to the next step for managing error,basically whenever the EXIT_FAILURE constants is found passed in an exit() function argument then the program will pause the execution of that particular block(eg. if block). and proceed to the next section of the code.

Similarly EXIT_SUCCESS constants will be used to show successful termination of program.



If you any have doubt,suggestion regarding this post or website then feel free to share with us.
 
If you have learned something new from this post then share this post with your family and
friends.
 
Happy Learning :)😎  

2 Comments

  1. Gyansetu's Programming courses are a fantastic resource for aspiring coders. Their structured approach and dedicated instructors create an ideal learning environment. Whether you're starting from scratch or honing your skills, Gyansetu has the tools you need to succeed in the world of programming!
    For more info:- https://www.gyansetu.in/blogs/70-power-bi-mcq-and-answers-with-explanation/

    ReplyDelete
  2. Gyansetu's Programming courses are a fantastic resource for aspiring coders. Their structured approach and dedicated instructors create an ideal learning environment. Whether you're starting from scratch or honing your skills, Gyansetu has the tools you need to succeed in the world of programming!
    For more info:- https://www.gyansetu.in/blogs/70-power-bi-mcq-and-answers-with-explanation/

    ReplyDelete
Previous Post Next Post