When to throw an exception?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Should I throw an exception in the following scenario?

I have a user class. The constructor takes one argument, the sessionid of
the user. This sessionid corresponds to an entry in a database. The
constructor calls the database with the passed in sessionid to retrieve the
user info. If the database call returns no rows, should I throw an exception
or return some kind of error code from the constructor?
 
Larry,
I would recommend a Manager (or whatever name) class that you could call Manager.GetUser(userId). Using this method, you could simply return a User object or null. I would also mark the User constructor as internal based off your description.

Jason Newell, MCAD
Software Engineer
 
Still, should I throw an exception in the constructor of the user class which
can then be caught by the manager class?
 
Larry,
Exceptions are rather expensive. It would be better to have the manager
class query the database. If there is no info, return null. Otherwise create
a class object and fill in the info that was returned.
Bob
 
Echo what Bob said. Sorry for not being clear enough. The User class should not ever get created if the Manager does not find a matching record in the database.

Jason Newell, MCAD
Software Engineer
 
Bob Milton said:
Exceptions are rather expensive. It would be better to have the manager
class query the database. If there is no info, return null. Otherwise create
a class object and fill in the info that was returned.

I think it really depends on how exceptional it is to ask for something
which isn't there. If it indicates a significant programming error, and
the whole request should be aborted anyway, then there's nothing wrong
with using an exception IMO.

The "exceptions are expensive" idea is a bit of a myth in my view.
They're only going to end up being expensive in a significant way of
you throw many, many thousand exceptions. As a rough indication, my
laptop can throw of the order of 100,000 exceptions in a second. If
you're throwing anything *like* that number, you're using exceptions in
the wrong way in the first place, and have bigger worries than
performance, IMO.
 
Is this something that could legitimely happens ? If no throw an exception.

In this partiuclar case I would rather expect to have a new line created for
me in the db assuming this is the first time I deal with this partiuclar
session but it all depends on what it's supposed to do...

Patrice
 
Back
Top