473,385 Members | 1,707 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,385 software developers and data experts.

[Semi-OT] About Exception Handling

Some time ago, I remember reading a discussion about the strengths and
weaknesses of exception handling. One of the weaknesses that was put
forward was that exception handling is inefficient (in the way of CPU
usage), compared to the "normal" practise returning values.

How true is this? Will using using exception handling, in general, be
much less efficient than returning values, or less efficient at all?

Just curious...

TIA
Nov 15 '05 #1
9 2506
"C# Learner" <cs****@learner.here> wrote in message
news:go********************************@4ax.com...
Some time ago, I remember reading a discussion about the strengths and
weaknesses of exception handling. One of the weaknesses that was put
forward was that exception handling is inefficient (in the way of CPU
usage), compared to the "normal" practise returning values.

How true is this? Will using using exception handling, in general, be
much less efficient than returning values, or less efficient at all?


Hi C# Learner,

In C#, exception handling doesn't cost you anything until an exception is
actually raised. While there is a performance hit, it is generally not
significant enough to care about and the benefits outweigh the drawbacks of
the old method of returning error values.

When you use exception handling, you gain a lot more information about what
is happening in your application. Just think about the basic Exception
object, there is a message, StackTrace, and other properties that give you a
lot of insight into what happened when the exception was raised.
Additionally, you can define your own custom exceptions when one of the many
exceptions that ship with the BCL doesn't meet your needs. When an
exception is raised, you can't ignore or forget about it because it is in
your face. You also have much more flexibility in how you handle
exceptions, as opposed to results from a method, with stack unwinding,
unhandled exception handlers, and cool stuff like that.

Joe
--
http://www.csharp-station.com

Nov 15 '05 #2
As Joe Mayo mentioned, exceptions aren't all that inefficient as long as no exceptions are actually thrown. However, you should assume that throwing exceptions is very expensive. Essentially, you should never use exceptions for normal control flow. Throw exceptions only in truly exceptional cases -- cases that should rarely or never come up in actual program runs. If you're throwing and catching exceptions often, it's not only bad style, but can also be a pretty severe performance hit

-- Ada

----- C# Learner wrote: ----

Some time ago, I remember reading a discussion about the strengths an
weaknesses of exception handling. One of the weaknesses that was pu
forward was that exception handling is inefficient (in the way of CP
usage), compared to the "normal" practise returning values

How true is this? Will using using exception handling, in general, b
much less efficient than returning values, or less efficient at all

Just curious..

TI

Nov 15 '05 #3
I agree with your point to avoid exceptions for normal control flow but it
seems like there's no other way to handle some things in .Net

Example :
How do you detect the end of stream of a BinaryReader? There might be a
better way but that's the most efficient one I found for now.

=========== start code ===========
BinaryReader br = new BinaryReader(File.OpenRead(@"c:\test.txt"));

while (true)
{
try
{
byte current = br.ReadByte();
}
catch (EndOfStreamException e)
{
// The end of the stream was detected, time to get out of the loop
break;
}
}
=========== end code ===========

Yves

"AdamMil" <an*******@discussions.microsoft.com> schreef in bericht
news:35**********************************@microsof t.com...
As Joe Mayo mentioned, exceptions aren't all that inefficient as long as no exceptions are actually thrown. However, you should assume that throwing
exceptions is very expensive. Essentially, you should never use exceptions
for normal control flow. Throw exceptions only in truly exceptional cases --
cases that should rarely or never come up in actual program runs. If you're
throwing and catching exceptions often, it's not only bad style, but can
also be a pretty severe performance hit.
-- Adam

----- C# Learner wrote: -----

Some time ago, I remember reading a discussion about the strengths and weaknesses of exception handling. One of the weaknesses that was put
forward was that exception handling is inefficient (in the way of CPU
usage), compared to the "normal" practise returning values.

How true is this? Will using using exception handling, in general, be much less efficient than returning values, or less efficient at all?

Just curious...

TIA

Nov 15 '05 #4
The best way to detect an end of stream is to use ReadBytes. It returns with a
read result of 0 if 0 bytes
are read and hence 0 bytes are available and the stream is at an end. You also
have PeekChar which returns
-1 if no more data is available on the stream. I would recommend against using
exceptions to control your
program flow, especially in the case of files where other methods exist.
--
Justin Rogers
DigiTec Web Consultants, LLC.
Blog: http://weblogs.asp.net/justin_rogers

"phoenix" <pa******@skynetWORK.be> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...
I agree with your point to avoid exceptions for normal control flow but it
seems like there's no other way to handle some things in .Net

Example :
How do you detect the end of stream of a BinaryReader? There might be a
better way but that's the most efficient one I found for now.

=========== start code ===========
BinaryReader br = new BinaryReader(File.OpenRead(@"c:\test.txt"));

while (true)
{
try
{
byte current = br.ReadByte();
}
catch (EndOfStreamException e)
{
// The end of the stream was detected, time to get out of the loop
break;
}
}
=========== end code ===========

Yves

"AdamMil" <an*******@discussions.microsoft.com> schreef in bericht
news:35**********************************@microsof t.com...
As Joe Mayo mentioned, exceptions aren't all that inefficient as long as

no exceptions are actually thrown. However, you should assume that throwing
exceptions is very expensive. Essentially, you should never use exceptions
for normal control flow. Throw exceptions only in truly exceptional cases --
cases that should rarely or never come up in actual program runs. If you're
throwing and catching exceptions often, it's not only bad style, but can
also be a pretty severe performance hit.

-- Adam

----- C# Learner wrote: -----

Some time ago, I remember reading a discussion about the strengths

and
weaknesses of exception handling. One of the weaknesses that was put
forward was that exception handling is inefficient (in the way of CPU
usage), compared to the "normal" practise returning values.

How true is this? Will using using exception handling, in general,

be
much less efficient than returning values, or less efficient at all?

Just curious...

TIA


Nov 15 '05 #5
I'm working with bytes not chars. When I use PeekChar I always get
"conversion buffer overflow" as error. What I really would need is PeekByte
which isn't available though (which I find pretty odd since it is a
BinairyReader after all). PeekChar would mean more exception handling in
stead of less.
Using ReadBytes forces me to use an array (of length 1 ...) which I didn't
want.

The best solution I could come up with was not using the BinaryReader but
using the Stream class. Then I could use Stream.ReadByte of which I could
use the return value to detect EOF (-1).

I wonder though what the difference in cost/performance is between doing the
check each time you read a byte or just catching that 1 exception.

Yves

"Justin Rogers" <Ju****@games4dotnet.com> schreef in bericht
news:u7**************@TK2MSFTNGP11.phx.gbl...
The best way to detect an end of stream is to use ReadBytes. It returns with a read result of 0 if 0 bytes
are read and hence 0 bytes are available and the stream is at an end. You also have PeekChar which returns
-1 if no more data is available on the stream. I would recommend against using exceptions to control your
program flow, especially in the case of files where other methods exist.
--
Justin Rogers
DigiTec Web Consultants, LLC.
Blog: http://weblogs.asp.net/justin_rogers

"phoenix" <pa******@skynetWORK.be> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...
I agree with your point to avoid exceptions for normal control flow but it seems like there's no other way to handle some things in .Net

Example :
How do you detect the end of stream of a BinaryReader? There might be a
better way but that's the most efficient one I found for now.

=========== start code ===========
BinaryReader br = new BinaryReader(File.OpenRead(@"c:\test.txt"));

while (true)
{
try
{
byte current = br.ReadByte();
}
catch (EndOfStreamException e)
{
// The end of the stream was detected, time to get out of the loop
break;
}
}
=========== end code ===========

Yves

"AdamMil" <an*******@discussions.microsoft.com> schreef in bericht
news:35**********************************@microsof t.com...
As Joe Mayo mentioned, exceptions aren't all that inefficient as long as
no exceptions are actually thrown. However, you should assume that throwing exceptions is very expensive. Essentially, you should never use exceptions for normal control flow. Throw exceptions only in truly exceptional cases -- cases that should rarely or never come up in actual program runs. If you're throwing and catching exceptions often, it's not only bad style, but can
also be a pretty severe performance hit.

-- Adam

----- C# Learner wrote: -----

Some time ago, I remember reading a discussion about the
strengths and
weaknesses of exception handling. One of the weaknesses that was
put forward was that exception handling is inefficient (in the way of CPU usage), compared to the "normal" practise returning values.

How true is this? Will using using exception handling, in general, be
much less efficient than returning values, or less efficient at

all?
Just curious...

TIA



Nov 15 '05 #6
Another solution would be to actually interrogate the underlying Stream
class when using the BinaryReader class:

while NotEOF(br)
{
byte current = br.ReadByte();
....
}

private bool NotEOF(BinaryReader br)
{
return br.Stream.Position < br.Stream.Length;
}

I havent compiled this, but the concept is correct.

Nick.
"phoenix" <pa******@skynetWORK.be> wrote in message
news:%2****************@TK2MSFTNGP11.phx.gbl...
I'm working with bytes not chars. When I use PeekChar I always get
"conversion buffer overflow" as error. What I really would need is PeekByte which isn't available though (which I find pretty odd since it is a
BinairyReader after all). PeekChar would mean more exception handling in
stead of less.
Using ReadBytes forces me to use an array (of length 1 ...) which I didn't
want.

The best solution I could come up with was not using the BinaryReader but
using the Stream class. Then I could use Stream.ReadByte of which I could
use the return value to detect EOF (-1).

I wonder though what the difference in cost/performance is between doing the check each time you read a byte or just catching that 1 exception.

Yves

"Justin Rogers" <Ju****@games4dotnet.com> schreef in bericht
news:u7**************@TK2MSFTNGP11.phx.gbl...
The best way to detect an end of stream is to use ReadBytes. It returns with a
read result of 0 if 0 bytes
are read and hence 0 bytes are available and the stream is at an end. You also
have PeekChar which returns
-1 if no more data is available on the stream. I would recommend
against using
exceptions to control your
program flow, especially in the case of files where other methods exist.
--
Justin Rogers
DigiTec Web Consultants, LLC.
Blog: http://weblogs.asp.net/justin_rogers

"phoenix" <pa******@skynetWORK.be> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...
I agree with your point to avoid exceptions for normal control flow but
it seems like there's no other way to handle some things in .Net

Example :
How do you detect the end of stream of a BinaryReader? There might be
a better way but that's the most efficient one I found for now.

=========== start code ===========
BinaryReader br = new BinaryReader(File.OpenRead(@"c:\test.txt"));

while (true)
{
try
{
byte current = br.ReadByte();
}
catch (EndOfStreamException e)
{
// The end of the stream was detected, time to get out of the loop
break;
}
}
=========== end code ===========

Yves

"AdamMil" <an*******@discussions.microsoft.com> schreef in bericht
news:35**********************************@microsof t.com...
> As Joe Mayo mentioned, exceptions aren't all that inefficient as long
as no exceptions are actually thrown. However, you should assume that throwing exceptions is very expensive. Essentially, you should never use exceptions for normal control flow. Throw exceptions only in truly exceptional cases -- cases that should rarely or never come up in actual program runs. If you're throwing and catching exceptions often, it's not only bad style, but
can also be a pretty severe performance hit.
>
> -- Adam
>
> ----- C# Learner wrote: -----
>
> Some time ago, I remember reading a discussion about the
strengths and
> weaknesses of exception handling. One of the weaknesses that
was put > forward was that exception handling is inefficient (in the way
of
CPU > usage), compared to the "normal" practise returning values.
>
> How true is this? Will using using exception handling, in general, be
> much less efficient than returning values, or less efficient at all? >
> Just curious...
>
> TIA
>



Nov 15 '05 #7
C# Learner <cs****@learner.here> wrote:
Some time ago, I remember reading a discussion about the strengths and
weaknesses of exception handling. One of the weaknesses that was put
forward was that exception handling is inefficient (in the way of CPU
usage), compared to the "normal" practise returning values.

How true is this? Will using using exception handling, in general, be
much less efficient than returning values, or less efficient at all?

Just curious...

TIA


Thanks for the replies.
Nov 15 '05 #8
Nick <fr**@here.com> wrote:
Another solution would be to actually interrogate the underlying Stream
class when using the BinaryReader class:

while NotEOF(br)
{
byte current = br.ReadByte();
....
}


That assumes that the BinaryReader doesn't do any caching - if it does,
the stream will reach the end before the BinaryReader does.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #9
Thats a really good point Jon. From the codelet provided by Yves, no
non-default configurables for the classes used were defined. It seems the
BinaryReader is badly designed, as its PeekChar clearly fails when
processing binary data, and exceptions are used for normal control flow (if
I am reading through a file, I expect to get to the end at some point). If
I was dealing with this problem, I would simply use the stream direct:

Stream sr = File.OpenRead(@"c:\test.txt");
int current;
while ((current = sr.ReadByte()) != -1)
{
Console.Write((char)current);
}
Console.ReadLine();
Nick.

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Nick <fr**@here.com> wrote:
Another solution would be to actually interrogate the underlying Stream
class when using the BinaryReader class:

while NotEOF(br)
{
byte current = br.ReadByte();
....
}


That assumes that the BinaryReader doesn't do any caching - if it does,
the stream will reach the end before the BinaryReader does.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #10

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

Similar topics

2
by: Dennis M. Marks | last post by:
I am never sure of when a semi-colon is required in javascript. Is there a definite rule? -- Dennis M. Marks -----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----...
7
by: jhomp ssens | last post by:
I would like to create a pulldown menu which is semi-transparent....that is, you can see the text and graphics behind it when it is pulled down. The effect I'm looking for can be seen at...
16
by: Kiuhnm | last post by:
Is there an elegant way to deal with semi-circular definitions? Semi-circular definition: A { B }; B { *A }; Circular reference: A { *B }; B { *A }; The problems arise when there are more...
2
by: David Scemama | last post by:
Hi, I'm looking for a way to display semi graphic characters in a multi line text control or in a rich text control. I've tried with all the characters of the extended ASCII table (code page...
27
by: StevePBurgess | last post by:
With a string of authors such as: Carson, David, Milne, Rebecca, Pakes, Francis J., Shalev, Karen, Shawyer, Andrea I would like to write a function to change every other comma into a semi...
2
by: Trond Michelsen | last post by:
Hi. I have a transparent PNG-image that I would like to display on top of the rest of the web page. I've already got this part working. But, I'd like the background (as in "the part of the image...
2
by: James Stroud | last post by:
Hello All, I am trying to create a semi-standalone with the vendor python on OS X 10.4 (python 2.3.5). I tried to include some packages with both --packages from the command and the 'packages'...
0
by: James Arnold | last post by:
I am trying to use a semi transparent PNG as the form background, allowing you to see through certain parts. The intention is similar to a skinnable form like launchy, with semi-transparent pixels...
9
by: JamesF1982 | last post by:
Hey everyone, My question is related to HTML, Javascript, CSS and ASP.NET but i think it belongs here! Upon an event i am trying to add a semi-transparent colour across the page so the...
26
by: machineghost | last post by:
First off, let me just say that as someone with no DBA training whatsoever, any help I can get with this issue will be very, very much appreciated. My company recently migrated our database from...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
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,...

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.