I have a problem. I must throw an exception in the constructor One() but do not know how do I suppose to catch it. 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
{
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.
#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:
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 ...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.