473,396 Members | 2,109 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Calling function that may throw an exception

Hello, I'm working with a hash table that is encapsulated in a class. One of
its member functions insert() throws an exception
if the insertion fails (for example, if the value was already present in the
hash table). Now I have client code that looks like this:

bool exception_thrown = false;

try
{
hash_table.insert(some_value);
}
catch(const std::runtime_error& e)
{
std::cerr << e.what() << std::endl;

exception_thrown = true;
}

if(!exception_thrown)
{
std::cout << some_value << " successfully inserted." << std::endl; /* For
debugging purposes, it would be nice to see position here */
}

Using the flag variable exception_thrown strikes me as a bit ugly...how
should I deal with this? If I'm calling a function that
may throw an exception I want to catch that exception. I can change the hash
table class itself if I need to..maybe the insert()
member function should return some error code instead but runtime_error
seems a bit more convenient since it can (should I think)
contain a description of the error. Please advise.

/ Eric
Jul 22 '05 #1
12 1840
Eric Lilja wrote:
Hello, I'm working with a hash table that is encapsulated in a class. One of
its member functions insert() throws an exception
if the insertion fails (for example, if the value was already present in the
hash table). Now I have client code that looks like this:

bool exception_thrown = false;

try
{
hash_table.insert(some_value);
}
catch(const std::runtime_error& e)
{
std::cerr << e.what() << std::endl;

exception_thrown = true;
}

if(!exception_thrown)
{
std::cout << some_value << " successfully inserted." << std::endl; /* For
debugging purposes, it would be nice to see position here */
}

Using the flag variable exception_thrown strikes me as a bit ugly...how
should I deal with this? If I'm calling a function that
may throw an exception I want to catch that exception. I can change the hash
table class itself if I need to..maybe the insert()
member function should return some error code instead but runtime_error
seems a bit more convenient since it can (should I think)
contain a description of the error. Please advise.


There was a discussion here recently "Arguments *Against* Exception Use".
Check it out. There was the note by Herb Sutter reminding us that one
shouldn't confuse normal functionality (and processing thereof) with
exceptional situations. If your hash table is _allowed_ to indicate that
insertion didn't happen and that's normal, then it has to be a return code
and not an exception. Something like that, anyway.

V
Jul 22 '05 #2
* Victor Bazarov:
Eric Lilja wrote:
Hello, I'm working with a hash table that is encapsulated in a class. One of
its member functions insert() throws an exception
if the insertion fails (for example, if the value was already present in the
hash table). Now I have client code that looks like this:

bool exception_thrown = false;

try
{
hash_table.insert(some_value);
}
catch(const std::runtime_error& e)
{
std::cerr << e.what() << std::endl;

exception_thrown = true;
}

if(!exception_thrown)
{
std::cout << some_value << " successfully inserted." << std::endl; /* For
debugging purposes, it would be nice to see position here */
}

Using the flag variable exception_thrown strikes me as a bit ugly...how
should I deal with this? If I'm calling a function that
may throw an exception I want to catch that exception. I can change the hash
table class itself if I need to..maybe the insert()
member function should return some error code instead but runtime_error
seems a bit more convenient since it can (should I think)
contain a description of the error. Please advise.


There was a discussion here recently "Arguments *Against* Exception Use".
Check it out. There was the note by Herb Sutter reminding us that one
shouldn't confuse normal functionality (and processing thereof) with
exceptional situations. If your hash table is _allowed_ to indicate that
insertion didn't happen and that's normal, then it has to be a return code
and not an exception. Something like that, anyway.


It's very easy to have both.

In terms of both efficiency and simplicity the best is to build the
exception-throwing one as a wrapper around the return-code one.

But I remember I argued at least halfway successfully once for doing
it the opposite way when a higher layer calls a lower layer of software.
The reason for that is that what is an exception at a lower layer
(e.g. unable to send mail) at some higher level becomes an expected and
quite normal thing (e.g. report that to the user). But the argument is
mostly for trolling purposes, because the assumption that both these
layers are involved in the same design is not a well-founded one... ;-)

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #3

"Eric Lilja" <er*******************@yahoo.com> wrote in message
news:cn**********@news.island.liu.se...
Hello, I'm working with a hash table that is encapsulated in a class. One
of its member functions insert() throws an exception
if the insertion fails (for example, if the value was already present in
the hash table). Now I have client code that looks like this:

bool exception_thrown = false;

try
{
hash_table.insert(some_value);
}
catch(const std::runtime_error& e)
{
std::cerr << e.what() << std::endl;

exception_thrown = true;
}

if(!exception_thrown)
{
std::cout << some_value << " successfully inserted." << std::endl; /*
For debugging purposes, it would be nice to see position here */
}

Using the flag variable exception_thrown strikes me as a bit ugly...how
should I deal with this?
Well you can certainly simplify the code, no flag is needed

try
{
hash_table.insert(some_value);
std::cout << some_value << " successfully inserted." << std::endl;
}
catch(const std::runtime_error& e)
{
std::cerr << e.what() << std::endl;
}
If I'm calling a function that
may throw an exception I want to catch that exception. I can change the
hash table class itself if I need to..maybe the insert()
member function should return some error code instead but runtime_error
seems a bit more convenient since it can (should I think)
contain a description of the error. Please advise.


insert() could return a status object that contains the error message if
things go wrong.

john
Jul 22 '05 #4

"Victor Bazarov" <v.********@comAcast.net> wrote in message
news:Yk*****************@newsread1.dllstx09.us.to. verio.net...
Eric Lilja wrote:
Hello, I'm working with a hash table that is encapsulated in a class. One
of its member functions insert() throws an exception
if the insertion fails (for example, if the value was already present in
the hash table). Now I have client code that looks like this:

bool exception_thrown = false;

try
{
hash_table.insert(some_value);
}
catch(const std::runtime_error& e)
{
std::cerr << e.what() << std::endl;

exception_thrown = true;
}

if(!exception_thrown)
{
std::cout << some_value << " successfully inserted." << std::endl; /*
For debugging purposes, it would be nice to see position here */
}

Using the flag variable exception_thrown strikes me as a bit ugly...how
should I deal with this? If I'm calling a function that
may throw an exception I want to catch that exception. I can change the
hash table class itself if I need to..maybe the insert()
member function should return some error code instead but runtime_error
seems a bit more convenient since it can (should I think)
contain a description of the error. Please advise.


There was a discussion here recently "Arguments *Against* Exception Use".
Check it out. There was the note by Herb Sutter reminding us that one
shouldn't confuse normal functionality (and processing thereof) with
exceptional situations. If your hash table is _allowed_ to indicate that
insertion didn't happen and that's normal, then it has to be a return code
and not an exception. Something like that, anyway.

V


Thanks for the reply. Say I change the hash table to return an error code
instead of
throwing an exception when the user is trying to insert a value that is
already present
in the hash table (a situation that strikes me as a bit too common to be
called exceptional),
what sort of a mechanism should I implement alongside it if the user wants a
more detailed
error description (could be useful for debugging purposes)?

I haven't checked out the thread you mentioned yet, but I will.

/ Eric
Jul 22 '05 #5

"John Harrison" <jo*************@hotmail.com> wrote in message
news:2v*************@uni-berlin.de...

"Eric Lilja" <er*******************@yahoo.com> wrote in message
news:cn**********@news.island.liu.se...
Hello, I'm working with a hash table that is encapsulated in a class. One
of its member functions insert() throws an exception
if the insertion fails (for example, if the value was already present in
the hash table). Now I have client code that looks like this:

bool exception_thrown = false;

try
{
hash_table.insert(some_value);
}
catch(const std::runtime_error& e)
{
std::cerr << e.what() << std::endl;

exception_thrown = true;
}

if(!exception_thrown)
{
std::cout << some_value << " successfully inserted." << std::endl; /*
For debugging purposes, it would be nice to see position here */
}

Using the flag variable exception_thrown strikes me as a bit ugly...how
should I deal with this?
Well you can certainly simplify the code, no flag is needed

try
{
hash_table.insert(some_value);
std::cout << some_value << " successfully inserted." << std::endl;
}
catch(const std::runtime_error& e)
{
std::cerr << e.what() << std::endl;
}


Wow, thanks John! After all this time spent learning C++ I never realised
that I could put
it in the same block after the call to the function-that-may-throw. Why
didn't I think of that?
Anyway, this new knowledge will clean up A LOT of my old programs > 100
lines!! Thanks!
If I'm calling a function that
may throw an exception I want to catch that exception. I can change the
hash table class itself if I need to..maybe the insert()
member function should return some error code instead but runtime_error
seems a bit more convenient since it can (should I think)
contain a description of the error. Please advise.

insert() could return a status object that contains the error message if
things go wrong.


Yeah, I'm thinking of changing the hash table class to do just that when the
user
is trying to perform an illegal insertion, which doesn't seem very
exceptional to
me. But as I said in my reply to Victor, I still would like the ability to
get a more
detailed error description, but how should I get that with numerical error
codes?
Some variant of errno but built-in in the class?
john


/ Eric
Jul 22 '05 #6
Eric Lilja wrote:
[...] Say I change the hash table to return an error code
instead of
throwing an exception when the user is trying to insert a value that is
already present
in the hash table (a situation that strikes me as a bit too common to be
called exceptional),
what sort of a mechanism should I implement alongside it if the user wants a
more detailed
error description (could be useful for debugging purposes)?


John has suggested it, and it seems like a decent solution, to return
a reference to a static object of the class... Of course, you could
easily marry the two concepts. It could be a pseudo-enumerator with
the value/comments and a real object:

template<class T>
class inserter { // your hash table or anything, essentially
class iterator {
...
virtual const std::string& what() const {
return inserter::everythingOK;
}
};

static std::string everythingOK;
static std::string insertionFailed;
static std::string otherError;

class insertionFailed_iterator : public iterator {
const std::string& what() const {
return inserter::insertionFailed;
}
};

class otherError_iterator : public iterator {
...
};

iterator insert(T t);
};
...
inserter<blah> mytable;

inserter::iterator it = mytable.insert(blah());
if (it == inserter::insertionFailed_iterator) {
// insertion failed
}
else {
// use 'it' here
}
Victor
Jul 22 '05 #7
Eric Lilja wrote:
I'm working with a hash table that is encapsulated in a class.
One of its member functions insert() throws an exception
if the insertion fails
(for example, if the value was already present in the hash table).
Now I have client code that looks like this:

bool exception_thrown = false;

try {
hash_table.insert(some_value);
This is a bad example.
The exception handling mechanism isn't necessary
unless the try block evaluates non-trivial expressions
with one or more operators that may throw exceptions.
}
catch(const std::runtime_error& e) {

std::cerr << e.what() << std::endl;

exception_thrown = true;
}

if (!exception_thrown) {

std::cout << some_value << " successfully inserted." << std::endl;
// For debugging purposes, it would be nice to see position here.
}

Using the flag variable exception_thrown strikes me as a bit ugly...
how should I deal with this? If I'm calling a function that
may throw an exception I want to catch that exception.

I can change the hash table class itself if I need to.
Maybe the insert() member function should return some error code instead
but runtime_error seems a bit more convenient
since it can (should I think) contain a description of the error.
Please advise.


I think that you need to redesign your hash table class.
Your insert(const SomeType&) method should return a value
so that it can be used in expressions.
It could return a reference to the has table object
or it could return an exception object.
Whether you decide to throw an exception of return an exception,
the exception object must contain enough information
about the exception to allow the calling program
to handle the exception and recover.
In this case, the exception object may contain a simple error code
or even a boolean value which simply indicates whether or not
the insertion failed. For example:

bool HashTable::insert(const SomeType&) {
// Return true if successful.
}

. . .

if (hash_table.insert(some_value)) {
std::cout << some_value << "successfully inserted."
<< std::endl;
}
Jul 22 '05 #8
"Eric Lilja" <er*******************@yahoo.com> wrote in
news:cn**********@news.island.liu.se:
insert() could return a status object that contains the error message
if things go wrong.


Yeah, I'm thinking of changing the hash table class to do just that
when the user
is trying to perform an illegal insertion, which doesn't seem very
exceptional to
me. But as I said in my reply to Victor, I still would like the
ability to get a more
detailed error description, but how should I get that with numerical
error codes?
Some variant of errno but built-in in the class?


Assuming that insert returns an error code on failure (and 0 on success),
what "more detailed error description" could you want more than EEXIST?
(Not sure if errno.h is Standard or not.. might be POSIX).

If insert were only returning a bool, maybe... but only if there were
multiple reasons as to why the insert could fail....
Jul 22 '05 #9
> what sort of a mechanism should I implement alongside it if the user wants a
more detailed
error description (could be useful for debugging purposes)?


Please consider that exceptions can not be ignored by the programmer
without additional instructions.
Would you like to guarantee that library users must react to a thrown
"notification"?

Regards,
Markus
Jul 22 '05 #10
> But as I said in my reply to Victor, I still would like the ability to
get a more
detailed error description, but how should I get that with numerical error
codes?
Some variant of errno but built-in in the class?


Does the discussion "conversion: errno => exception" offer interesting
and useful informations for you?
http://groups.google.de/groups?threa...ing.google.com

Regards,
Markus
Jul 22 '05 #11
> bool HashTable::insert(const SomeType&) {
// Return true if successful.
}


How easy is it to forget to check the return code?

Have you got resource limitations or constraints like in EC++ to
exclude the usage of exceptions?
Jul 22 '05 #12
Ma************@web.de (Markus Elfring) wrote in message news:<40**************************@posting.google. com>...
bool HashTable::insert(const SomeType&) {
// Return true if successful.
}


How easy is it to forget to check the return code?


Easy. However, there are situations in which it is reasonable
to use a bool return value to indicate duplicates. You definitely
need to keep that condition separate from std::bad_alloc.
Ignoring duplicates may be a sane strategy.

Regards,
Michiel Salters
Jul 22 '05 #13

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

Similar topics

2
by: Ascaron | last post by:
Hi there! I’m having a strange problem with a c++ dll that is called from a c# program. The dll wraps a large piece of c++ software that uses exceptions for its error-signalling. To keep the...
1
by: W1ld0ne [MCSD] | last post by:
In VB6 dlls' I could get the path of the calling web site by using the COM+ class library and the ASP class library. Does anyone have a clue how to do this in VB.Net The objective is to have...
4
by: Bugs | last post by:
Hi, I wonder if anyone can help me out. I'm building a vb.net application that has a form with a panel that contains several other sub forms (as a collection of controls). What I'm wanting to...
2
by: ramasubramanian.rahul | last post by:
hi i am trying to call some java APIs from c . i use the standatd JNI calls to load the JVM from a c program and call all java functions by using a pointer to the jvm which was returned by the JNI...
4
by: j_depp_99 | last post by:
The program below fails on execution and I think the error is in my pop function but it all looks correct.Also could someone check my code as to why my print function is not working? I havent...
8
by: Jeff | last post by:
Still new to vb.net in VS2005 web developer... What is the proper/standard way of doing the following - setting the value of a variable in one sub and calling it from another? E.g., as below....
28
by: Jess | last post by:
Hello, It is said that if I implement a "swap" member function, then it should never throw any exception. However, if I implement "swap" non- member function, then the restriction doesn't...
28
by: gnuist006 | last post by:
I have some code like this: (if (test) (exit) (do something)) or (if (test)
1
by: George2 | last post by:
Hello everyone, As far as I know, C function does not throw exception. But Bjarne said in his book, section 14.8 Exception and Efficiency, -------------------- In particular, an...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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...
0
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
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.