473,472 Members | 2,148 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

catch exception

class A
{
public:
A()
{
try
{
p = new int;
//Other lines that may throw exception.
}
catch(...)
{
delete p;
}

private:
int *p;
};

In the above code, catch the exception in A's constructor to delete p.
Is it OK? Is there a better way to delete p?

Thanks.

Jack
Aug 22 '08 #1
7 1628
ju******@gmail.com wrote in news:33ee848b-a4f5-44e9-86dd-
9b**********@v26g2000prm.googlegroups.com:
class A
{
public:
A()
{
try
{
p = new int;
//Other lines that may throw exception.
}
catch(...)
{
delete p;
}

private:
int *p;
};

In the above code, catch the exception in A's constructor to delete p.
Is it OK? Is there a better way to delete p?
It will work... what would be better is to use some sort of smart pointer
class, such as std::auto_ptr. Assuming you need the dynamic allocation in
the first place (In this simple example, it makes no sense to make p
dynamic at all...)

Example:
class A
{
public:
A() : p(new int)
{
// Other potentially throwing code
}

private:
std::auto_ptr<intp;
};

Aug 22 '08 #2
On Aug 22, 2:15*pm, junw2...@gmail.com wrote:
class A
{
public:
* * A()
* * {
* * * * *try
* * * * *{
* * * * * * * *p = new int;
* * * * * * * *//Other lines that may throw exception.
* * * * *}
* * * * *catch(...)
* * * * *{
* * * * * * * *delete p;
* * * * *}

private:
* * *int *p;

};

In the above code, catch the exception in A's constructor to delete p.
Is it OK? Is there a better way to delete p?
Yes it's OK (modulo the missing closing brace), but better is:

class A
{
public:
A() : p(new int(0))
{
// do other stuff which may throw
}

private:
some_smart_pointer_type<intp;

};

Now if that stuff throws, the smart pointer for p will be destroyed,
which will delete p.
Pick your smart pointer -- see boost and tr1. Or, if you know this
object won't be getting copied, or you have a deep copy constructor,
you could use std::auto_ptr

Aug 22 '08 #3
On Aug 22, 11:15 pm, junw2...@gmail.com wrote:
class A
{
public:
A()
{
try
{
p = new int;
//Other lines that may throw exception.
}
catch(...)
{
delete p;
}

private:
int *p;

};
If 'new int' throws, you'll be deleting an uninitialized pointer which
is UB.
It is safer and simpler to use a smart pointer.

HTH,

--
gpd
Aug 22 '08 #4
Andre Kostur wrote:
ju******@gmail.com wrote in news:33ee848b-a4f5-44e9-86dd-
9b**********@v26g2000prm.googlegroups.com:
>class A
{
public:
A()
{
try
{
p = new int;
//Other lines that may throw exception.
}
catch(...)
{
delete p;
}

private:
int *p;
};

In the above code, catch the exception in A's constructor to delete p.
Is it OK? Is there a better way to delete p?

It will work...
Really? What will be the value of p if 'new' throws?

Wouldn't it be better like this:

A(): p(0)
{
try
{
p = new int;
}
catch(...)
{
delete p;
}
}
Aug 23 '08 #5
Juha Nieminen <no****@thanks.invalidwrote in news:t5Qrk.51$ME2.22
@read4.inet.fi:
>
Really? What will be the value of p if 'new' throws?

Wouldn't it be better like this:

A(): p(0)
{
try
{
p = new int;
}
catch(...)
{
delete p;
}
}
It depends upon what you are after, In the previous case, if new
throws, p is never assigned a value and A is never constructed. If all
of your resources are wrapped in RAII classes (such as auto_ptr), then
anything constructed prior to the new throwing will be cleaned up as the
exception leaves A's constructor. This is all done for you. The code
you provided really doesn't do anything. If the new throws, then p
won't need deleted. If the new works, then it won't be deleted. If you
didn't want the new to prevent the construction of A, then you could do
something like:

A()
{
try
{
std::auto_ptr<intp(new int);
//do stuff with p
// p gets automatically deleted as it leaves this scope.
} catch(...)
{ // don't really care if the above worked or not
}

// do other stuff
}

-or-

A()
{
try
{
p.reset(new int);
//do stuff with p
// p gets automatically deleted when A gets deleted.
} catch(...)
{ // don't really care if the above worked or not
}

// do other stuff
std::auto_ptr<intp;
}
Both of these would prevent the allocation of p from preventing the
construction of A (though if you are really that low on memory, do you
really want to carry on?) and will automatically handle the deletion of
the object when A is destroyed.

Generally speaking (meaning there are always special cases) I think
Andre's solution is the cleanest for most uses.
joe
Aug 23 '08 #6
On Aug 22, 2:57*pm, gpderetta <gpdere...@gmail.comwrote:
On Aug 22, 11:15 pm, junw2...@gmail.com wrote:
class A
{
public:
* * A()
* * {
* * * * *try
* * * * *{
* * * * * * * *p = new int;
* * * * * * * *//Other lines that may throw exception.
* * * * *}
* * * * *catch(...)
* * * * *{
* * * * * * * *delete p;
* * * * *}
private:
* * *int *p;
};

If 'new int' throws, you'll be deleting an uninitialized pointer which
is UB.
It is safer and simpler to use a smart pointer.

HTH,

--
gpd
In fact, smart pointer will also delete p. Theoretically, they are the
same, rigth?

Jack
Aug 24 '08 #7
On Aug 24, 2:24 am, junw2...@gmail.com wrote:
On Aug 22, 2:57 pm, gpderetta <gpdere...@gmail.comwrote:
On Aug 22, 11:15 pm, junw2...@gmail.com wrote:
class A
{
public:
A()
{
try
{
p = new int;
//Other lines that may throw exception.
}
catch(...)
{
delete p;
}
private:
int *p;
};
If 'new int' throws, you'll be deleting an uninitialized pointer which
is UB.
It is safer and simpler to use a smart pointer.


In fact, smart pointer will also delete p.
The smart pointer will not delete 'p', 'p' will be the smart pointer :

struct A() {

A() p(new int) { /* do something with p */ }
private:
std::auto_ptr<intp;
};
Theoretically, they are the
same, rigth?
Wrong. If 'new int' trows, the smart pointer won't have been
constructed yet, so its destructor won't be called.

OTOH, if you instead reset p to 'new int' in the body of the
constructor, the smart pointer will have been default constructed. If
'new int' throws, p destructor will be called, but destroying a
default constructed smart pointer will not lead to UB (well, at least
for any reasonable smart pointer).

In general, the less you use try/catch, the easier is not to make
mistakes. RAII is your friend.

HTH,

--
gpd
Aug 24 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Gary.Hu | last post by:
I was trying to catch the Arithmetic exception, unsuccessfully. try{ int a = 0, b = 9; b = b / a; }catch(...){ cout << "arithmetic exception was catched!" << endl; } After ran the program,...
7
by: Noor | last post by:
please tell the technique of centralize exception handling without try catch blocks in c#.
5
by: Jacek Dziedzic | last post by:
Hi! In my main() function I have a last-resort exception construct that looks like this: int main() { try { // ... program code }
11
by: Pohihihi | last post by:
I was wondering what is the ill effect of using try catch in the code, both nested and simple big one. e.g. try { \\ whole app code goes here } catch (Exception ee) {}
13
by: Benny | last post by:
Hi, I have something like this: try { // some code } catch // note - i am catching everything now {
23
by: VB Programmer | last post by:
Variable scope doesn't make sense to me when it comes to Try Catch Finally. Example: In order to close/dispose a db connection you have to dim the connection outside of the Try Catch Finally...
3
by: will | last post by:
Hi all. I've got an question about how to catch an exception. In Page_Load, I place a DataGrid, dg1, into edit mode. This will call the method called GenericGridEvent. GenericGridEvent will call...
2
by: Ralph Krausse | last post by:
I created a try/catch/finally but when an expection is thrown, the catch does not handle it... (I know this code is wrong, I want to force the error for this example) try { DataSet ds = new...
11
by: l.woods | last post by:
I want to set up my CATCH for a specific exception, but I really don't know which one of the multitude that it is. I am getting the exception now with Catch ex as Exception but I want to be...
32
by: cj | last post by:
Another wish of mine. I wish there was a way in the Try Catch structure to say if there wasn't an error to do something. Like an else statement. Try Catch Else Finally. Also because I...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.