Try statement in C? [closed]
Is there is a try statement in C? I wan to make an "area calculator" of a trapezoid. I would expect the users to input numbers only:
#include <stdio.h>
#include <conio.h>
main()
{
clrscr();
float base1, base2, height, area;
printf("This program will compute the area of your trapezoid. Enjoy!");
printf("\n\tPlease enter the length of base1: ");
scanf("%f", &base1);
printf("\tPlease enter the length of base2: ");
scanf("%f", &base2);
printf("\tPlease 开发者_C百科enter the length of height: ");
scanf("%f", &height);
area = (base1 + base2) * h / 2;
printf("\nThe area of your trapezoid is: ", area);
getch();
}
But then, they have the freedom of inputting non-numeric data. Doing so will crash the program. What can I do to check if it is the right data? I believe this can be done with a loop but since there are many solutions to one program i doubt that mine is the most efficient.
C does not have exceptions and hence does not have a try
statement, it is a C++ feature, not a C one. You can set up something similar yourself using longjmp()
/setjmp()
, although personally I'd avoid trying to reinvent that wheel.
No it doesn't
Generally try statements only exist in object-oriented languages such as Python, C++, Objective-C, C#, Visual Basic, Java etc.
Error handling is made explicitely in C, with if()
and goto
. Exception handling (such as division by 0) depends on the underlying kernel (signal handling on Unix, CPU trap handling on most RTOS).
Ada has an exception
mechanism with the ability to raise
user defined exceptions.
精彩评论