程序小白天天打卡(关于assert函数和捕获异常)

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;
	}
	
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值