一、noexcept的用法
#include<iostream>
using std::cout;
using std::endl;
/*
任务1:编写函数,展示作为声明符的 noexcept,noexcept(true),noexcept(false)的区别
任务2:展示noexcept不能区分重载
任务3:在noexcept函数中抛出异常
任务4:展示noexcept作为运算符的效果
*/
void foo() noexcept { throw 1; } //注意:因为冲突,此函数运行会报错
//void foo(){} //noexcept不能作为重载标志
void tao() noexcept(1){}
void zen() noexcept(1-1){}
int main()
{
cout << "foo() noexcept : " << noexcept(foo()) << "\n"
//<<"foo(): "<<noexcept(foo())<<" \n"
<< "tao() noexcept(1) " << noexcept(tao()) << "\n"
<< "zen() noexcept(1-1): " << noexcept(zen()) << "\n";
cout << "Calling foo() noexcept {throw 1} : ";
//foo(); //调用会报错
}
结果如上图所示。
二、捕获派生异常
#include<iostream>
#include"Vec3D.h"
#include"RangeException.h"
using std::cout;
using std::endl;
//任务4:在主函数中创建Vec3D对象并调用[]制造越界问题
//捕获异常并输出异常中的信息
int main()
{
Vec3D v{ 3.5,2.1,8.6};
try
{
std::cout << (v/ 0.0)[0] << std::endl;
}
catch (RangeException &e)
{
std::cout << "Exception :" << e.what() << std::endl;
std::cout << "Vector dimension is " << e.getDimension() << std::endl;
std::cout << "You used index " << e.getIndex() << std::endl;
}
catch (ZeroException& e)
{
std::cout << "Exception: " << e.what() << std::endl;
}
return 0;
}
结果如上图所示
相关文件
#pragma once
#include<iostream>
#include<exception>
//任务2:创建RangeException 类
//定义构造函数 RangeException(std::size_t dimension,const int index)
class RangeException:public std::out_of_range
{
private:
std::size_t dimension{ 3 };
int index{ 0 };
public:
RangeException(std::size_t dimension, int index)
:out_of_range("index exceedsVector dimension")
{
this->dimension = dimension;
this->index = index;
}
std::size_t getDimension()
{
return dimension;
}
int getIndex()
{
return index;
}
};
#pragma once
#include<stdexcept>
#include<exception>
//
class ZeroException :public std::runtime_error
{
public:
ZeroException() :runtime_error("Divided by 0.0") {}
ZeroException(const char* msg) :runtime_error(msg) {}
};
#pragma once
#include<array>
#include<cmath>
#include<limits>
#include"RangeException.h"
#include"ZeroException.h"
class Vec3D
{
public:
constexpr static std::size_t DIMENSION = 3;
private:
std::array<double, 3> vec{ 1.0,1.0,1.0 };
bool isSame(double a, double b)
{
return std::fabs(a - b) < std::numeric_limits<double>::epsilon();
}
public:
Vec3D() = default;
Vec3D(double x, double y, double z)
{
vec[0] = x;
vec[1] = y;
vec[2] = z;
}
double& operator[](const int index)
{
if (index >= 0 && index <= 2)
{
return vec[index];
}
else
{
throw RangeException(3, index);
}
}
Vec3D operator/(const double divisor)
{
Vec3D t(*this);
if (isSame(divisor, 0.0))
{
throw ZeroException();
}
else
{
for (auto& i : t.vec)
{
i /= divisor;
}
}
return t;
}
};