关于c++中的异常处理机制主要是try...catch
语句,下面给出了一个除数为0的异常处理程序代码。
- 基本语句代码详见下例:
//hmtian
#include<iostream>
template<class T>
T div(T x, T y)
{
if (y == 0)
{
throw y;
}
return x / y;
}
template<class T>
void test()
{
try
{
div<int>(3, 0);
}
catch (T y)
{
std::cout << "Divisor cannot be" << y << std::endl;
}
catch (...)
{
std::cout << "unexpected";
}
}
void test1() throw(int, float)//限定抛出异常类型
{
try
{
div<float>(3.00, 0.00);
}
catch (float y)
{
std::cout << "Divisor cannot be" << y << std::endl;
}
catch (...)
{
std::cout << "unexpected";
}
}
int main()
{
test<int>();
test1();
system("pause");
}
- 栈解旋
异常被抛出后,从进入try块起,到异常被抛掷前,这期间在栈上的构造的所有对象,都会被自动析构。析构的顺序与构造的顺序相反,这一过程称为栈的解旋(unwinding)。
#include<iostream>
template<class T>
class test
{
public:
test(T a, T b) : x(a), y(b)
{
std::cout << "Constructor" << std::endl;
std::cout << "result:" << div(x, y) << std::endl;
}
~test()
{
std::cout << "Destructor" << std::endl;
}
T div(T x, T y)
{
if (y == 0)
{
throw y;
}
return x / y;
}
private:
T x, y;
};
template<class T>
void divtest(T x, T y)
{
try
{
test<T> t1(x, y), t2(x+3,y+2);
}
catch ( T y)
{
std::cout << "Divisor cannot be" << y << std::endl;
}
}
template<class T>
void my_divtest(T x, T y) noexcept
{
test<T>(x, y);
}
int main()
{
divtest<int>(3,1);
divtest<int>(3,0);
//my_divtest<int>(3, 0);
system("pause");
}
运行结果如下:
- 关于noexpect的用法:
现在我们将上述main()
函数中的注释去掉之后再次运行会有以下结果:
可以看到程序直接终止运行,如果被noexcept修饰的函数抛出了异常,编译器直接选择调用标准库里面的 std::terminate()直接终止程序,比throw()在处理异常的效率要高些,有效的防治了异常的扩散传播
如果你对自己的函数有自信觉得不会抛出异常,你可以使用noexpect
,反之,如果程序终止了,那可能错误就出现在加了关键字noexpect
的函数这里。