473,881 Members | 1,562 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Q: Exceptions and when to use them

Hi,

somehow the prejudice of exceptions being rather slow (compared to,
ie. returning an error value and checking that) keeps sticking around ..
at least around me. I guess this is also why I refrained from using them
often. But are they 'slow' in general?

I guess it also depends on how, when and where you use them. What I
am looking for is a sort of guideline that explains where exceptions are
approriate and where they are not. The name 'exception' implies to me,
that you should not use them to notify the caller of 'warnings', but use
return values for that kind of 'error' instead. But this is rather just
a guess, which is why I am posting here, to hear your advice.

With this post, I am not trying to ditch exceptions. I do not know
much about their use, so please excuse wording, that might sound
flame-ish.

Thank you!
--
jb

(reply address in rot13, unscramble first)
Jul 23 '05 #1
10 1558
Jakob Bieling wrote:
[snip, re: exceptions]
I guess it also depends on how, when and where you use them.


You throw an exception when the promises the interface
makes cannot be kept.

So, that implies that the interface has to make promises,
has to have its required inputs and promised outputs made
explicit. One term for this is "programmin g to a contract."
Each function will have requirements for what it can accept
as inputs, and make promises about the side effects it
can produce and the values it can return.

This does not tell you enough to design good functions.
But it gives you an idea how to correctly implement
exceptions when you do have good functions.

Basically, stuff that is normal, predictable behaviour
for a function, probably should be handled through the
regular interface. Stuff that is not that may be better
as an exception. That way, you handle the routine stuff
in the interface, and deal with it in client code as
routine stuff. The rare stuff, or the weird stuff, you
handle through the exception mechanism.

In one of the "standard references" everybody recomends,
there's a story about sending somebody to cut the lawn.
And there's various things that could happend.
- He could find the lawnmower, and cut the lawn. Return
message is "yes, ok, done."
- The lawnmower could be out of fuel. So, he has to fill
it and then go on. Should be the same result. And it's
an ordinary occurence. Shouldn't be an exception.
The guy should handle it inside his task. So, he might
have a "cut the lawn" task that includes "check for fuel"
and "fill with fuel" as sub-tasks.
- It could be bucketing down rain, and so cutting the lawn
could be impossible. Result: Return the message "can't
cut the lawn right now, try later." Probably you want
to include this as part of the task, as it's a fairly
regular occurence. So it would go through the regular
interface.
- The lawnmower could be in the garage, the garage could
be locked. What now? Not the ordinary thing, so got to
go get the person with the keys and do something unusual.
That might be an exception, as the keys might be someplace
that is not easily available.
- The lawnmower could be missing. (Borrowed, stolen, not put
back in the right place, etc.) Again, this is outside the
ordinary nature of the task, so it's an exception.

So you get the notion of "ordinary part of the task" and
"not ordinary part of the task." And it depends on context.
Socks

Jul 23 '05 #2
Ian
Jakob Bieling wrote:
Hi,

somehow the prejudice of exceptions being rather slow (compared to,
ie. returning an error value and checking that) keeps sticking around ..
at least around me. I guess this is also why I refrained from using them
often. But are they 'slow' in general?
Provided you only use them for genuine exception conditions (well
illustrated in the post form "Socks") they shouldn't be slower and in
some case may be quicker and lead to clearer code. You may run into
issues with some compilers (one I have to use consumes ridiculous
amounts of stack with exceptions).

You can reasonably expect throwing and catching an exception to be
relatively expensive.

Try a simple example in your environment:

int f() { return 0; }

int main()
{
<start a timer>
for( unsigned n = 0; n < someBigNumber; ++n )
{
if( 0 != f() )
{
<print error>
}
}
<check time>
<start a timer>
for( unsigned n = 0; n < someBigNumber; ++n )
{
try
{
f();
}
catch(...)
{
<print error>
}
}
<check time>
}

Ian
I guess it also depends on how, when and where you use them. What I
am looking for is a sort of guideline that explains where exceptions are
approriate and where they are not. The name 'exception' implies to me,
that you should not use them to notify the caller of 'warnings', but use
return values for that kind of 'error' instead. But this is rather just
a guess, which is why I am posting here, to hear your advice.

With this post, I am not trying to ditch exceptions. I do not know
much about their use, so please excuse wording, that might sound
flame-ish.

Thank you!

Jul 23 '05 #3

"Jakob Bieling" <ar************ ****@rot13.com> wrote in message
news:d7******** *****@news.t-online.com...
Hi,

somehow the prejudice of exceptions being rather slow (compared to,
ie. returning an error value and checking that) keeps sticking around ..
at least around me. I guess this is also why I refrained from using them
often. But are they 'slow' in general?
Well yes, they are slow since they imply a try-catch block and a partial
stack unwind upon a thrown exception. However, when exceptions are used for
what they are meant for (i.e: exceptional conditions for exceptional
circumstances) their performance and the flexibility they provide is hard to
do without.

I guess it also depends on how, when and where you use them. What I
am looking for is a sort of guideline that explains where exceptions are
approriate and where they are not. The name 'exception' implies to me,
that you should not use them to notify the caller of 'warnings', but use
return values for that kind of 'error' instead. But this is rather just
a guess, which is why I am posting here, to hear your advice.

With this post, I am not trying to ditch exceptions. I do not know
much about their use, so please excuse wording, that might sound
flame-ish.


You won't be chastised for ditching exceptions, lol. To those that say that
exceptions shouldn't be used to change a normal program's sequence, i'ld
agree.

But exceptions lets you throw an object which includes diagnostic
information about the error that just occured (thats priceless). This
implies much (you can attempt recovery, log the error, display the error,
throw another Exception, prompt the user, etc). Basicly, at that point where
the thrown exception was caught, you are still dealing with an application
that is potentially recoverable (that too is priceless).

As a simple example, here is a file reader with a diagnostic error reporting
mechanism.
Change the file name to trigger the exception and display the catch-block's
e.what()'s output. You could just as easily wrap the try-catch block in a
do-while loop prompting the user to correct the anomaly displayed and
try-again or quit. Beats generating an exit-return upon the exceptional
condition.

// freader.cpp
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <stdexcept>

int main()
{
std::ifstream ifs;
std::string s_buffer;
std::vector<std ::string> vs;
try
{
ifs.open("fread er.cpp");
if (!ifs)
{
throw std::exception( "(!ifs) while opening file.");
}

while (std::getline(i fs, s_buffer)) // getline until failure
{
vs.push_back(s_ buffer);
}

if (!ifs.eof()) // if failure was not an eof marker, throw
{
throw std::exception( "(!ifs.eof( )) while reading file.");
}

typedef std::vector<std ::string>::iter ator VITER;
for (VITER it = vs.begin(); it != vs.end(); ++it)
{
std::cout << *it << std::endl;
}
} // end of try block
catch (const std::exception& e)
{
std::cout << "Error !!\n" << e.what() << "\n";
} // catch

return 0;
}

Jul 23 '05 #4

"Jakob Bieling" <ar************ ****@rot13.com> skrev i en meddelelse
news:d7******** *****@news.t-online.com...
Hi,

somehow the prejudice of exceptions being rather slow (compared to, ie.
returning an error value and checking that) keeps sticking around .. at
least around me. I guess this is also why I refrained from using them
often. But are they 'slow' in general?
That depends on how they are implemented. On e.g. Microsofts 32-bit
compilers and GCC on Windows, there is some overhead, but it is quite
possible to implement exceptions with no cost whatsoever if you do not throw
them. So far as I know, gcc on Linux have implemented them this way. Notice
that in this case using exceptions is faster then checking return-codes.
What matters more is that the codes written using exceptions is usually
clearer than code not using them: the main path contain
I guess it also depends on how, when and where you use them. What I am
looking for is a sort of guideline that explains where exceptions are
approriate and where they are not. The name 'exception' implies to me,
that you should not use them to notify the caller of 'warnings', but use
return values for that kind of 'error' instead. But this is rather just a
guess, which is why I am posting here, to hear your advice.
Use exceptions in cases where you encounter an error you can't handle and
which you do not expect to be handled by the code that immediately calls
you. For errors that you expect to be handled by your immediate caller, use
a status code instead (if this is possible).
This is a matter of judgement of course, and in cases where you are in
doubt, you might supply two functions - one that guarantees succes and one
that assumes the caller will check the value.

/Peter

With this post, I am not trying to ditch exceptions. I do not know much
about their use, so please excuse wording, that might sound flame-ish.

Thank you!
--
jb

(reply address in rot13, unscramble first)


Jul 23 '05 #5
Peter Koch Larsen wrote:
"Jakob Bieling" <ar************ ****@rot13.com> skrev i en meddelelse
news:d7******** *****@news.t-online.com...
Hi,

somehow the prejudice of exceptions being rather slow (compared to,
ie.
returning an error value and checking that) keeps sticking around .. at
least around me. I guess this is also why I refrained from using them
often. But are they 'slow' in general?


That depends on how they are implemented. On e.g. Microsofts 32-bit
compilers and GCC on Windows, there is some overhead, but it is quite
possible to implement exceptions with no cost whatsoever if you do not
throw them. So far as I know, gcc on Linux have implemented them this way.


I'm wondering whether that's actually true. Maybe no additional code gets
executed as long as no exception is thrown, but still there is a lot of
additional code needed for stack unwinding in the case an exception is
thrown. This seems to significantly enlarge the total code size, which in
turn lowers the cache effectiveness. And cache misses tend to be very
expensive on modern 32/64bit platforms.

Jul 23 '05 #6

"Rolf Magnus" <ra******@t-online.de> skrev i en meddelelse
news:d7******** *****@news.t-online.com...
Peter Koch Larsen wrote:
"Jakob Bieling" <ar************ ****@rot13.com> skrev i en meddelelse
news:d7******** *****@news.t-online.com...
Hi,

somehow the prejudice of exceptions being rather slow (compared to,
ie.
returning an error value and checking that) keeps sticking around .. at
least around me. I guess this is also why I refrained from using them
often. But are they 'slow' in general?


That depends on how they are implemented. On e.g. Microsofts 32-bit
compilers and GCC on Windows, there is some overhead, but it is quite
possible to implement exceptions with no cost whatsoever if you do not
throw them. So far as I know, gcc on Linux have implemented them this
way.


I'm wondering whether that's actually true. Maybe no additional code gets
executed as long as no exception is thrown, but still there is a lot of
additional code needed for stack unwinding in the case an exception is
thrown. This seems to significantly enlarge the total code size, which in
turn lowers the cache effectiveness. And cache misses tend to be very
expensive on modern 32/64bit platforms.

First, I have no actual experience with gcc: my information is from this
group (or its moderated cousin). With this reservation I believe my
statement is accurate.
I do not understand your questioning of cache-effectiveness. So long as the
exceptions are not made, they need not be part of the cache. Also, my
understanding is that they will not - exception related code is "put away"
to avoid this. Of course if an exception is actually thrown, it is going to
be costly to unwind - but if this is a rare case it should not matter.

/Peter
Jul 23 '05 #7
Peter Koch Larsen wrote:
"Jakob Bieling" <ar************ ****@rot13.com> skrev i en meddelelse
news:d7******** *****@news.t-online.com...
Hi,

somehow the prejudice of exceptions being rather slow (compared
to, ie. returning an error value and checking that) keeps sticking
around .. at least around me. I guess this is also why I refrained
from using them often. But are they 'slow' in general?


That depends on how they are implemented. On e.g. Microsofts 32-bit
compilers and GCC on Windows, there is some overhead,


FWIW, some months ago I experimented with this (GCC 3.3.3, MinGW port on Windows) for a speed-critical maths library.
The conclusion was that - for my particular code - compiling with exceptions enabled roughly doubled execution time
_even if there was no exception throwing/catching code present_. I've not retested with newer versions of GCC, nor with
other compilers.

--
Lionel B

Jul 23 '05 #8


Lionel B wrote:
Peter Koch Larsen wrote:
"Jakob Bieling" <ar************ ****@rot13.com> skrev i en meddelelse
news:d7****** *******@news.t-online.com...
Hi,

somehow the prejudice of exceptions being rather slow (compared
to, ie. returning an error value and checking that) keeps sticking
around .. at least around me. I guess this is also why I refrained
from using them often. But are they 'slow' in general?


That depends on how they are implemented. On e.g. Microsofts 32-bit
compilers and GCC on Windows, there is some overhead,

FWIW, some months ago I experimented with this (GCC 3.3.3, MinGW port on Windows) for a speed-critical maths library.
The conclusion was that - for my particular code - compiling with exceptions enabled roughly doubled execution time
_even if there was no exception throwing/catching code present_. I've not retested with newer versions of GCC, nor with
other compilers.


I've noticed a 5x speed degradation in some some benchmark tests, but it
does seem to be compiler dependent and with GCC the results varied
wildly from release to release.

Jul 23 '05 #9

"Hang Dog" <ri*******@wobb le.net> skrev i en meddelelse
news:3g******** ****@individual .net...


Lionel B wrote:
Peter Koch Larsen wrote:
"Jakob Bieling" <ar************ ****@rot13.com> skrev i en meddelelse
news:d7***** ********@news.t-online.com...

Hi,

somehow the prejudice of exceptions being rather slow (compared
to, ie. returning an error value and checking that) keeps sticking
around .. at least around me. I guess this is also why I refrained
from using them often. But are they 'slow' in general?

That depends on how they are implemented. On e.g. Microsofts 32-bit
compilers and GCC on Windows, there is some overhead,

FWIW, some months ago I experimented with this (GCC 3.3.3, MinGW port on
Windows) for a speed-critical maths library.
The conclusion was that - for my particular code - compiling with
exceptions enabled roughly doubled execution time
_even if there was no exception throwing/catching code present_. I've not
retested with newer versions of GCC, nor with
other compilers.


I've noticed a 5x speed degradation in some some benchmark tests, but it
does seem to be compiler dependent and with GCC the results varied wildly
from release to release.

So far as I know, it is only the gcc version on Linuz that generates the
"no-overhead" exception code. I do not know why, but it probably is related
to the way the Windows "structured exception handling" is integrated.

/Peter
Jul 23 '05 #10

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

Similar topics

21
2246
by: dkcpub | last post by:
I'm very new to Python, but I couldn't find anything in the docs or faq about this. And I fished around in the IDLE menus but didn't see anything. Is there a tool that can determine all the exceptions that can be raised in a Python function, or in any of the functions it calls, etc.? /Dan
26
2927
by: OvErboRed | last post by:
I just read a whole bunch of threads on microsoft.public.dotnet.* regarding checked exceptions (the longest-running of which seems to be <cJQQ9.4419 $j94.834878@news02.tsnz.net>. My personal belief is that checked exceptions should be required in .NET. I find that many others share the same views as I do. It is extremely frustrating to have to work around this with hacks like Abstract ADO.NET and CLRxLint (which still don't solve the...
24
2509
by: mag31 | last post by:
Is there any way to find out if a particular .net function will throw an exception without first generating the exception? I am using structured exception handling i.e. try catch finally blocks with a top level catch all for Exception. However, I would like to be able to catch most .net exceptions when they are generated. I would then be able to generate a valuable exception message and do something about it!!! Hence the question above....
6
2836
by: RepStat | last post by:
I've read that it is best not to use exceptions willy-nilly for stupid purposes as they can be a major performance hit if they are thrown. But is it a performance hit to use a try..catch..finally block, just in case there might be an exception? i.e. is it ok performance-wise to pepper pieces of code with try..catch..finally blocks that must be robust, in order that cleanup can be done correctly should there be an exception?
8
2263
by: cat | last post by:
I had a long and heated discussion with other developers on my team on when it makes sense to throw an exception and when to use an alternate solution. The .NET documentation recommends that an exception should be thrown only in exceptional situations. It turned out that each of my colleagues had their own interpretation about what an "exceptional situation" may actually be. First of all, myself I’m against using exceptions extensively,...
1
2400
by: Anonieko | last post by:
Understanding and Using Exceptions (this is a really long post...only read it if you (a) don't know what try/catch is OR (b) actually write catch(Exception ex) or catch{ }) The first thing I look for when evaluating someone's code is a try/catch block. While it isn't a perfect indicator, exception handling is one of the few things that quickly speak about the quality of code. Within seconds you might discover that the code author...
4
1858
by: Steve | last post by:
I have read a couple articles online, read my Jesse Liberty book but I am still confused as to just what the best practices are for using exceptions. I keep changing how I'm working with them and it has now, after 15k lines of code resulted in a royal mess! It's my hope to ask some specific questions with scenario examples and that some of you might offer a little guidance or general suggestions. 1) string...
2
2973
by: Zytan | last post by:
I know that WebRequest.GetResponse can throw WebException from internet tutorials. However in the MSDN docs: http://msdn2.microsoft.com/en-us/library/system.net.webrequest.getresponse.aspx It only lists NotImplementedException in the Exceptions section. (Note that it does mention WebException in the Remarks section, but who knows if this is always the case for such classes, and thus perhaps they can't be trusted to always list these, and...
0
6510
RedSon
by: RedSon | last post by:
Chapter 3: What are the most common Exceptions and what do they mean? As we saw in the last chapter, there isn't only the standard Exception, but you also get special exceptions like NullPointerException or ArrayIndexOutOfBoundsException. All of these extend the basic class Exception. In general, you can sort Exceptions into two groups: Checked and unchecked Exceptions. Checked Exceptions are checked by the compiler at compilation time. Most...
0
9927
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11098
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...
0
10717
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9552
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...
0
7109
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5781
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
5977
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4597
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
2
4196
muto222
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.