开发者

Try statement in C? [closed]

开发者 https://www.devze.com 2023-04-11 09:31 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消