C++ 为什么可以';在构造函数中捕获异常?
我有这个测试代码来处理构造函数中的异常。 函数f()创建一个被零除的异常,但不会捕获此异常。 相反,如果我抛出一个自定义整数,则会捕获异常C++ 为什么可以';在构造函数中捕获异常?,c++,exception,constructor,C++,Exception,Constructor,我有这个测试代码来处理构造函数中的异常。 函数f()创建一个被零除的异常,但不会捕获此异常。 相反,如果我抛出一个自定义整数,则会捕获异常 #include <iostream> using namespace std; class A { public: void f(){ int x; x=1/0; //throw 10; } A(){ try{ f(); } catch(int e){ co
#include <iostream>
using namespace std;
class A
{
public:
void f(){
int x;
x=1/0;
//throw 10;
}
A(){
try{
f();
}
catch(int e){
cout << "Exception caught\n";
}
}
};
int main (int argc, const char * argv[])
{
A a;
return 0;
}
#包括
使用名称空间std;
甲级
{
公众:
void f(){
int x;
x=1/0;
//投掷10枚;
}
(){
试一试{
f();
}
捕获(INTE){
CUT< P>一个除以零的整数不是标准的C++异常。因此,你不能依赖于一个隐式地抛出异常。一个特定的编译器可能会把分界映射成一个异常(你需要检查编译器文档)。但是,请注意,这不是可移植的行为,也不适用于所有编译器
您最好自己检查错误条件(除数等于零),并显式抛出异常
class A
{
public:
void f()
{
int x;
//For illustration only
int a = 0;
if(a == 0)
throw std::runtime_error( "Divide by zero Exception");
x=1/a;
}
A()
{
try
{
f();
}
catch(const std::runtime_error& e)
{
cout << "Exception caught\n";
cout << e.what();
}
}
};
A类
{
公众:
void f()
{
int x;
//仅供说明
int a=0;
如果(a==0)
抛出std::runtime_错误(“除零异常”);
x=1/a;
}
()
{
尝试
{
f();
}
捕获(const std::runtime_error&e)
{
CUT< P>零除法不是C++异常。< /P>
看看这里的答案:还有。注意,整数除以零,任何事情都可能发生,包括崩溃、鼻魔和程序员怀孕。