2018/2/12
C++
1. 关于assert函数
1.使用
assert函数是基于c语言库的函数,所以调用时要用头文件#include<cassert>
2.功能
assert函数可以调试程序,可以利用它在某个程序的关键假设不成立时立刻
停止函数的执行并且报错
3.例子
/*使用assert函数来调试程序,判断程序的输入条件是否正常*/
#include<iostream>
#include<stdlib.h>
#include<cassert>//使用基于C语言的头文件
using namespace std;
void main()
{
int num;
cout << "请输入一个10以内的自然数" << endl;
cin >> num;
assert(num < 10 && num >0);//如果输入数不满足assert的条件,则程序报错
system("pause");
}
//若输入一个不为10以内的自然数,程序立即报错
2.捕获异常
try
{//Do somthing
//Throw something
}
catch
{
//Do ever;
}
2.每条try语句至少要有一条配对的catch语句,定义catch语句来确定一个特定函数的参数
使用throw来抛出异常
3.使用模板
type functionName(argument)throw(type);
#include<iostream>
#include<stdlib.h>
#include<climits>
using namespace std;
/*采用了捕获异常的方法,throw一个字符串出来*/
/*const表示不能改变的量*/
unsigned long returnFactorial(unsigned short num)throw(const char*);
int main()
{
int num;
cout << "请输入一个整数";
cin >> num;
try
{
unsigned long factorial = returnFactorial(num);
cout << num << "的阶乘是" << factorial;
}
catch (const char*e)//捕获异常
{
cout << e;
}
system("pause");
}
unsigned long returnFactorial(unsigned short num)throw(const char*)
{
long sum = 1;
long max = ULONG_MAX;
for (int i = 1; i <=num; i++)
{
sum *= i;
max /= i;
}
if (max < 1)
{
throw("该基数阶乘值太大,无法去计算");
}
else
{
return sum;
}
}