473,796 Members | 2,688 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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_throw n = false;

try
{
hash_table.inse rt(some_value);
}
catch(const std::runtime_er ror& e)
{
std::cerr << e.what() << std::endl;

exception_throw n = true;
}

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

Using the flag variable exception_throw n 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 1883
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_throw n = false;

try
{
hash_table.inse rt(some_value);
}
catch(const std::runtime_er ror& e)
{
std::cerr << e.what() << std::endl;

exception_throw n = true;
}

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

Using the flag variable exception_throw n 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_throw n = false;

try
{
hash_table.inse rt(some_value);
}
catch(const std::runtime_er ror& e)
{
std::cerr << e.what() << std::endl;

exception_throw n = true;
}

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

Using the flag variable exception_throw n 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.c om> 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_throw n = false;

try
{
hash_table.inse rt(some_value);
}
catch(const std::runtime_er ror& e)
{
std::cerr << e.what() << std::endl;

exception_throw n = true;
}

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

Using the flag variable exception_throw n 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.inse rt(some_value);
std::cout << some_value << " successfully inserted." << std::endl;
}
catch(const std::runtime_er ror& 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.********@com Acast.net> wrote in message
news:Yk******** *********@newsr ead1.dllstx09.u s.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_throw n = false;

try
{
hash_table.inse rt(some_value);
}
catch(const std::runtime_er ror& e)
{
std::cerr << e.what() << std::endl;

exception_throw n = true;
}

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

Using the flag variable exception_throw n 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.c om> 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_throw n = false;

try
{
hash_table.inse rt(some_value);
}
catch(const std::runtime_er ror& e)
{
std::cerr << e.what() << std::endl;

exception_throw n = true;
}

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

Using the flag variable exception_throw n 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.inse rt(some_value);
std::cout << some_value << " successfully inserted." << std::endl;
}
catch(const std::runtime_er ror& 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::every thingOK;
}
};

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

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

class otherError_iter ator : public iterator {
...
};

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

inserter::itera tor it = mytable.insert( blah());
if (it == inserter::inser tionFailed_iter ator) {
// 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_throw n = false;

try {
hash_table.inse rt(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_er ror& e) {

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

exception_throw n = true;
}

if (!exception_thr own) {

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

Using the flag variable exception_throw n 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::inse rt(const SomeType&) {
// Return true if successful.
}

. . .

if (hash_table.ins ert(some_value) ) {
std::cout << some_value << "successful ly inserted."
<< std::endl;
}
Jul 22 '05 #8
"Eric Lilja" <er************ *******@yahoo.c om> 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
"notificati on"?

Regards,
Markus
Jul 22 '05 #10

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

Similar topics

2
352
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 exception mechanism away from the c# end, all functions in the dll are embedded in catch-all blocks that return ‘false’ if anything throws an exception. Using a c++ program as the caller, the dll can be shown to work and return false on an...
1
3593
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 an xml file containing some data sitting inside a web site. Now I want two or more sites to reside on the same server. I want them to use the same dll's. To open the xml file, I need to supply a path to it. How would I get this dll to automatically...
4
2255
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 do is call a generically named public sub in the top-most sub form in the panel. I have the name of the top-most form as a string (eg. g_TopForm = "frmCustomers") and I can reference the form with:
2
2828
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 call the source code is given below and also the errors .. Plz help in resolving these. This is a code being (slightly modified ) which was downloaded from SUN website :
4
2567
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 included the other parts of my program but will if someone needs it. Please help; I have had it. I have checked all C++ websites and cannot figure it out. <code> template<class Type> void Novice<Type>::Print()
8
12621
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. The code below draws an error as indicated. Surely there has to be a better way than to make xxx a session variable? Thanks
28
2857
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 apply. Can somebody tell me why? Thanks, Jess
28
3815
by: gnuist006 | last post by:
I have some code like this: (if (test) (exit) (do something)) or (if (test)
1
1404
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 implementation knows that only a few standard C library functions (such as atexit() and qsort()) can throw exceptions,
0
10452
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10169
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10003
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9050
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7546
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5440
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5569
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4115
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2924
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.