《C++面向对象程序设计(第4版)》学习笔记-11

在这里插入图片描述

此份笔记建议在完整阅读郑莉老师、董渊老师、何江舟老师所编写的《C++语言程序设计(第4版)》后食用,风味更佳!
最后,由于本人水平有限,笔记中仍存在错误但还没有被检查出来的地方,欢迎大家批评与指正。


第12章 异常处理

实例:编写一个的简单的求给定数平方根的程序,设计一个异常类用异常处理机制来检测给定数为负数的情况。在主函数中进行测试。

#include <iostream>
#include <cmath>
#include <stdexcept>
using namespace std;

double GetSqrt(double xx) throw(invalid_argument)
{
	if (xx < 0)
	{
		throw invalid_argument("the num should be positive");
	}
	return sqrt(xx);
}

int main()
{
	double x;
	double res;
	cout << "Please input num: ";
	cin >> x;
	try
	{
		res = GetSqrt(x);
		cout << "the result is: " << res << endl;
	}
	catch (exception &e)
	{
		cout << "Error: " << e.what() << endl;
	}
	while (1);
}

猜你喜欢

转载自blog.csdn.net/Jason3633/article/details/91966002