你可以在定义一个函数时明确地表明你想让他抛出一个异常,为了表明你想让他抛出哪种类型的异常可以使用如下所示语法:
type functionName(arguments)throw(type)
如果没有使用这种语法来定义函数,就意味着函数可以抛出任意类型异常。
使用异常的基本原则:应该只用他们来处理确实可能不正常的情况。
#include <iostream>
#include <climits>
//unsigned long returnFactorial(unsigned short num) throw (const char *);
unsigned long returnFactorial(unsigned short num) throw (const char *)
{
unsigned long sum = 1;
unsigned long max = ULONG_MAX;
for(int i = 1;i <= num;i++){
sum *= i;
max /= i;
}
if(max < 1){
throw "悲催。。。。。。。该基数太大,无法在计算机计算求出阶乘值。\n";
}else{
return sum;
}
}
int main(int argc, char const *argv[])
{
unsigned short num = 0;
std::cout << "请输入一个整数:" << "\n";
while(!(std::cin >> num) || num < 1){
std::cin.clear(); //清除状态
std::cin.ignore(); //清除缓冲区
std::cout << "请输入一个整数:" << "\n";
}
std::cin.ignore(100,'\n');
try
{
unsigned long factorial = returnFactorial(num);
std::cout << num << "的阶乘是:" << factorial << "\n";
}
catch(const char *e)
{
std::cout << e;
}
return 0;
}