【发布时间】:2026-02-13 14:45:01
【问题描述】:
我想使用断言测试 gcd 函数,但我不知道如何捕获异常(并防止程序崩溃)。
int gcd(int a, int b) {
if(a<0 || b<0) {
throw "Illegal argument";
}
if(a==0 || b==0)
return a+b;
while(a!=b) {
if(a>b) {
a = a - b;
}
else {
b = b - a;
}
}
return a;
}
void test_gcd() {
assert(gcd(16,24) == 8);
assert(gcd(0, 19) == 19);
try {
gcd(5, -15);
assert(false);
} catch (char* s) {
assert(true);
cout << "Illegal";
}
}
【问题讨论】:
-
assert不会抛出异常,它只是在打印出一些东西后终止程序。 -
另外,您应该将
throw与派生自std::exception的内容一起使用,而不是使用const char*文字。 -
assert(true)是多余的。
标签: c++ try-catch assert throw greatest-common-divisor