[英]C++ - Exception in Constructor
I have a problem.我有个问题。 I must throw an exception in the constructor One() but do not know how do I suppose to catch it.
我必须在构造函数 One() 中抛出一个异常,但不知道我该如何捕捉它。 Can someone suggest something?
有人可以建议吗? I have tried this method: Throwing exceptions from constructors , What happens if a constructor throws an exception?
我试过这个方法: 从构造函数抛出异常, 如果构造函数抛出异常会发生什么?
My code:我的代码:
class One
{
int a, b;
public:
One()
{
a = 7;
b = 0;
if (b == 0)
{
throw "except";
}
}
};
int main()
{
One j;
try
{
cout << "good";
}
catch(const char *str)
{
cout << str;
}
}
Place the variable definition inside the try
block:将变量定义放在
try
块中:
try
{
One j;
std::cout << "good";
}
catch(const char *str)
{
std::cout << str;
}
First of all, don't throw non exception.首先,不要抛出非异常。 2. If you call constructor inside the try block, you can catch it then.
2. 如果在 try 块内调用构造函数,则可以捕获它。
#include <iostream>
#include <stdexcept>
class One
{
int a, b;
public:
One():
a(7),
b(0)
{
if (b == 0) {
throw std::runtime_error("except");
}
}
};
...
try {
One j;
std::cout << "good" << std::endl;
} catch(std::exception& e) {
std::cerr << e.what() << std::endl;
}
Another solution if you don't want to have the whole code inside a try..catch block:如果您不想将整个代码放在 try..catch 块中,则另一种解决方案:
int main()
{
One* j = nullptr;
try
{
j = new One;
cout << "good";
} catch (const char *str)
{
cout << str;
return 0;
}
// continue with object in j ...
}
And of course you should a smart pointer in this case:当然,在这种情况下,您应该使用智能指针:
int main()
{
std::unique_ptr< One> j;
try
{
j.reset( new One()); // or use std::make_unique<>()
cout << "good";
} catch (const char *str)
{
cout << str;
return 0;
}
// continue with object in j ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.