I saw many examples but I am not able to understand, how to use try catch with a simple constructor, I wrote a sample program:
class A
{
public:
try {
A()
{ cout << "in costr\n"; throw 10;}
}//try closed
catch (int a)
{ cout << "caught 1 \n"; }
};
main()
{
A *ptr = new A;
}
- This program gives a compilation error
- If exception is caught, what happens to object ??
The
try/catchcode is supposed to be together, you can’t have one without the other. Something like this is what you’re after:See the following program for a complete working example:
With the
throw 42in there, you see:meaning that
mainhas caught the exception coming from the constructor. Without thethrow, you see:because everything has worked.
The main problems with your code seem to be:
You have a
trystatement where it shouldn’t be.Try/catchblocks should generally be within a function or method, you have it immediately after thepublickeyword.If you’re throwing an exception from the constructor, you don’t catch it in the constructor. Instead you catch it in the code that called the constructor (
mainin this case).As previously mentioned,
tryandcatchgo together, they’re not standalone entities.If you are trying to
throwandcatchwithin the constructor, you’ll still need to put it within the constructor itself, something like:which gives you:
Note specifically how the
try/catchblock is both complete and within the constructor function.