Search code examples
cexceptiontypesmismatch

How to Handle Data Type Mismatch Exception in C


Is it possible to handle data type mismatch exceptions in C?

In C++ and other higher-level languages, the code is usually surrounded by try...catch. However, since there is no exception handling mechanism in C, how do we handle data type mismatch exceptions?

For instance, let us assume that I have a program that requires the user to enter an integer number. If the user hits an alphabetic character by mistake, the program crashes. How can I take care of this in C?

Here is some sample code:

#include "stdafx.h"

void main()
{
    int x = 0;
    printf("Hello World!\n\n");
    printf("Please enter an integer: ");
    scanf("%d", &x);
    printf("\n");
    printf("The integer entered is %d", x);
    printf("\n\n");
    printf("Press any key to exit!");
    getchar();
    getchar();
}

Solution

  • I am going to assume that you are using scanf to handle input. the program should not crash. You need to read the manual page for scanf and in the section return values it tells you that the function returns the number of items matched. You compare this number with what is expected. If they differ you take the appropriate action.

    EDIT

    Some code for Matthew and Bart:

    int i;
    
    if (scanf("%d", &i) == 1)
    {
        printf("You have entered %d\n", i);
    }
    else
    {
        printf("You have entered an invalid number\n");
    }