472,976 Members | 1,233 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,976 software developers and data experts.

errors inside a constructor

Hi,

I have a class whose constructor accepts a filename and performs some actions
on it[1].

Some things might go wrong, such as not being the right kind of file, the file
doesn't exist, is read-only, etc...

I guess the only way to report an error inside a constructor is to raise an
exception, but it feels a bit extreme to raise an exception becuase a file
couldn't be found....

IS this the best design? Any comments would be appreciated. O:-)

[1] I don't think it's relevant but in case you're curious, it reads all the
version information on it (product name, comapny name, etc...)
Jul 19 '05 #1
7 2431
Boogie El Aceitoso wrote:
Hi,

I have a class whose constructor accepts a filename and performs some actions
on it[1].

Some things might go wrong, such as not being the right kind of file, the file
doesn't exist, is read-only, etc...

I guess the only way to report an error inside a constructor is to raise an
exception, but it feels a bit extreme to raise an exception becuase a file
couldn't be found....

IS this the best design? Any comments would be appreciated. O:-)


It all depends on what you're trying to do.

If you're doing somthing simple, batch mode - come in - go out - not
concering yourself with other kinds of things (like changes to the file
once it has been read) etc, then refusing to create the object by
throwing an exception is fine. However, if you're trying to do more
complex things, you might want to allow creation of the object and
handle the various states that the "concept" may be in. In other words,
it goes back to requirements. Maybe it is a flaw of mine but I try very
hard not to use exceptions.

Jul 19 '05 #2
Boogie El Aceitoso wrote:
Hi,

I have a class whose constructor accepts a filename and performs some actions
on it[1].

Some things might go wrong, such as not being the right kind of file, the file
doesn't exist, is read-only, etc...

I guess the only way to report an error inside a constructor is to raise an
exception, but it feels a bit extreme to raise an exception becuase a file
couldn't be found....

IS this the best design? Any comments would be appreciated. O:-)

[1] I don't think it's relevant but in case you're curious, it reads all the
version information on it (product name, comapny name, etc...)


I would throw an exception. Class constructors are meant to bring a
class object into a good state and establish an invariant that the other
member functions maintain when used. If you don't throw an exception,
and the class can not be used, then the user will have to check for a
result after creating each object of your class and your classes members
will either have to assume that the object is in a good state, or always
check before being used and signal an error which the user will have to
test at each call. Throwing an exception is the correct method.
Exceptions don't have to be just used for devastating errors.

I'm relatively new to C++, but that much has been drilled into me by Mr.
Stroustrup.

Jul 19 '05 #3
Boogie El Aceitoso escribió:
I have a class whose constructor accepts a filename and performs some actions
on it[1].

Some things might go wrong, such as not being the right kind of file, the file
doesn't exist, is read-only, etc...

I guess the only way to report an error inside a constructor is to raise an
exception, but it feels a bit extreme to raise an exception becuase a file
couldn't be found....


If the class need a valid file to be in a valid state, throw an
excepcion seems perfectly fine for me. And is easier catch the
excepction in an upper level that write a battery of if ...

And I don't see nothing extreme in the use of exceptions. Is an element
of the language like any other.

Regards.
Jul 19 '05 #4
"Boogie El Aceitoso" <fr****@telefonica.net> wrote...
I have a class whose constructor accepts a filename and performs some actions on it[1].

Some things might go wrong, such as not being the right kind of file, the file doesn't exist, is read-only, etc...

I guess the only way to report an error inside a constructor is to raise an exception, but it feels a bit extreme to raise an exception becuase a file
couldn't be found....

IS this the best design? Any comments would be appreciated. O:-)


There IS no "best" design. The design should be suited to your needs.

One more possibility is a member variable that would indicate success
or failure to construct your object properly. You could use it this
way:

MyClass obj(filename);

if (obj.good()) { // 'good' is an accessor to that member var
.. continue
}
else {
.. errors creating 'obj' (or processing the file)
}

Victor
Jul 19 '05 #5
> Hi,

I have a class whose constructor accepts a filename and performs some actions on it[1].

Some things might go wrong, such as not being the right kind of file, the file doesn't exist, is read-only, etc...

I guess the only way to report an error inside a constructor is to raise an exception, but it feels a bit extreme to raise an exception becuase a file
couldn't be found....

IS this the best design? Any comments would be appreciated. O:-)

[1] I don't think it's relevant but in case you're curious, it reads all the version information on it (product name, comapny name, etc...)


It's a religious issue. You could for instance establish an error state
instead and have the caller test your object for success or failure (let me
know if you need instructions on how to code this). You then do this:

CYourObject YourObject(Whatever);
if (YourObject)
{
// Success
}
else
{
// Failure
}

Of course you're then forced to always check for this and other developers
that might use your class will have to check as well. If not and your class
depends on the file being successfully opened then all other class methods
will have to be robust against failure. That is, they will all have check
the state of the file before processing or otherwise respond accordingly
when something fails because the file was never opened. This can get very
tedious of course (and code-intensive, something you want to avoid if
possible). In any case, your decision also depends on whether a "can't open
file" problem is really a critical error in this class. If it is and your
class really can't proceed without this file (and no separate "Open()"
method exists so the caller can correct the problem and try again) then an
exception is fine. In fact, I would even recommend it (I use them all the
time) and you need not even put a try/catch around it in many cases. You
need only do so in the top-level function only, especially where the
situation is considered a critical error and you need to back out of
everything you're doing. One caveat however. Your class' destructor won't be
called if its constructor throws an exception (standard C++ rule). So make
sure you release any other resources that you normally depend on your
destructor to free (as req'd).
Jul 19 '05 #6
On Mon, 03 Nov 2003 17:49:52 +0100, Boogie El Aceitoso
<fr****@telefonica.net> wrote:
I have a class whose constructor accepts a filename and performs some actions
on it[1].

Some things might go wrong, such as not being the right kind of file, the file
doesn't exist, is read-only, etc...

I guess the only way to report an error inside a constructor is to raise an
exception, but it feels a bit extreme to raise an exception becuase a file
couldn't be found....
Can you subsequently do anything sensible with the object if the
file access fails?

If yes, then set a member variable flag appropriately.

If not, then you have an exceptional situation. Throw the
exception.
IS this the best design? Any comments would be appreciated. O:-) [1] I don't think it's relevant but in case you're curious, it reads all the
version information on it (product name, comapny name, etc...)


Sincerely,

Gene Wirchenko

Jul 19 '05 #7
Boogie El Aceitoso wrote:
Hi,

I have a class whose constructor accepts a filename and performs some actions
on it[1].

Some things might go wrong, such as not being the right kind of file, the file
doesn't exist, is read-only, etc...

I guess the only way to report an error inside a constructor is to raise an
exception, but it feels a bit extreme to raise an exception becuase a file
couldn't be found....

IS this the best design? Any comments would be appreciated. O:-)

[1] I don't think it's relevant but in case you're curious, it reads all the
version information on it (product name, comapny name, etc...)


There is no best design, of course. But how does the istream class
handle file not found? You could take a hint from that.

Jul 19 '05 #8

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

Similar topics

3
by: Michael G | last post by:
I am getting some errors/warnings that I don't understand. This code is in a Java app that uses Swing J Components with an ActionListener. The code/errors/warnings follow. Thanks for any help,...
9
by: soni29 | last post by:
hi, i have written the following code, still in the learning stage: #include<iostream.h> class CBox { public: // Constructor definition CBox(double lv, double bv = 1.0, double hv = 1.0) :...
28
by: Daniel | last post by:
Hello =) I have an object which contains a method that should execute every x ms. I can use setInterval inside the object construct like this - self.setInterval('ObjectName.methodName()',...
2
by: Grumble | last post by:
Hello all, I came across the following definition (or is it declaration? I never know): struct OFFSET_AND_SIZE { INT64 offset; UINT64 size; OFFSET_AND_SIZE (INT64 o, UINT64 s) : offset...
2
by: Efkas | last post by:
I have a Win Form app, calling the consctructor of a class. Inside the class, I declare some stuff like new Label, etc. I want to add this label inside the constructor in the windows form by...
7
by: brett.estabrook | last post by:
I have written a multi-threaded c# windows service in .net 1.1 (Visual Studio .net 2003). The service has several threads that poll a Sql 6.5 database on another machine. Each thread will execute a...
8
by: 2b|!2b==? | last post by:
typedef struct llist_entry_s llist_entry; /* opaque type */ struct llist_entry_s { llist_entry * next; char * keyword; char * value; llist_entry() :next(0), keyword(0), value(0) {
9
by: Justin Voelker | last post by:
I have a configuration file that contains the host, username, password, and database name required for any database connections. The config file runs through a few if/then/else statements to...
3
by: r_ahimsa_m | last post by:
Hello, I am learning JavaScipt. I have written some functions and I verified my code using http://www.jslint.com/ validator. I don't understand the problems it reports. Could you help me please...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
4
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.