By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,583 Members | 1,042 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,583 IT Pros & Developers. It's quick & easy.

Exceptions and performance hit

P: n/a
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?
Nov 16 '05 #1
Share this Question
Share on Google+
6 Replies


P: n/a
RepStat,

It does not degrade performance to use a try catch block if an exception
is not thrown. It will start to impact performance only if an exception is
thrown and you catch it. The basic premise is to not throw an exception to
indicate status. Rather, an exception should do just that, indicate when
something exceptional has happened (which generally can not be recovered
from).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
"RepStat" <an*******@discussions.microsoft.com> wrote in message
news:0A**********************************@microsof t.com...
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?
Nov 16 '05 #2

P: n/a
The big performance hit is when you actually "throw" an exception. If the
code unfolds "normally" without throwing any exception you will get a very
small performance hit (some instruction that saves the state of the
registers when you enter the try block). I would not worry about it at all
and use try/finally (or rather the "using" construct) whenever some resource
needs to be freed (or some invariant restored).

On the other hand, I would recommend that you only use exceptions to deal
with "exceptional" situations and that you don't use them as "special
returns" because you will gain on performance and code clarity as well.

Good use of exceptions is a subtle issue. For example, if you have to open a
file that might or might not exist under "normal" conditions, you should
test its presence with File.Exists before opening it instead of opening it
and catching an exception. On the other hand, if the file is supposed to
exist under "normal" conditions (for example because it got created by
another method just before, or because it is installed by your setup and the
user is not supposed to fool around with it), you should not test it with
File.Exists and let the exception handling deal with the "exceptional" case
where the file does not exist. As you see, this requires a bit of subtlety
(is this condition "normal" or "exceptional"?) and some rigor in your
coding, but it is really worth the extra work.

Bruno.
"RepStat" <an*******@discussions.microsoft.com> a écrit dans le message de
news:0A**********************************@microsof t.com...
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?
Nov 16 '05 #3

P: n/a
Good answer!
Also resist the temptation to wrap exceptions in exceptions or wrapping all
your methods in a try. In other words, there is not much point in catching
an exception just to rethrow the same exception unless your throwing a
different exception (i.e. aggregating all unknown exceptions to one of your
own application exceptions). So you may have many methods that do not have
any try/catch blocks even if you expect an exception. If you would just
rethrow the same exception, why catch it? Let the caller would get the same
exception anyway. This assumes you don't have any cleanup code or closing
streams, etc. If you do, they try/finally or try/catch/finally works well.
So if you only want to ensure clean up of streams (etc.) you can just use
try/finally. If exception is thrown, your finally will run and the
exception will perk back up the chain so you don't have to rethrow it.

--
William Stacey, MVP

"Bruno Jouhier [MVP]" <bj******@club-internet.fr> wrote in message
news:#n**************@TK2MSFTNGP10.phx.gbl...
The big performance hit is when you actually "throw" an exception. If the
code unfolds "normally" without throwing any exception you will get a very
small performance hit (some instruction that saves the state of the
registers when you enter the try block). I would not worry about it at all
and use try/finally (or rather the "using" construct) whenever some resource needs to be freed (or some invariant restored).

On the other hand, I would recommend that you only use exceptions to deal
with "exceptional" situations and that you don't use them as "special
returns" because you will gain on performance and code clarity as well.

Good use of exceptions is a subtle issue. For example, if you have to open a file that might or might not exist under "normal" conditions, you should
test its presence with File.Exists before opening it instead of opening it
and catching an exception. On the other hand, if the file is supposed to
exist under "normal" conditions (for example because it got created by
another method just before, or because it is installed by your setup and the user is not supposed to fool around with it), you should not test it with
File.Exists and let the exception handling deal with the "exceptional" case where the file does not exist. As you see, this requires a bit of subtlety
(is this condition "normal" or "exceptional"?) and some rigor in your
coding, but it is really worth the extra work.

Bruno.
"RepStat" <an*******@discussions.microsoft.com> a écrit dans le message de
news:0A**********************************@microsof t.com...
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?


Nov 16 '05 #4

P: n/a

"William Stacey [MVP]" <st***********@mvps.org> a écrit dans le message de
news:e6**************@TK2MSFTNGP11.phx.gbl...
Good answer!
Also resist the temptation to wrap exceptions in exceptions or wrapping all your methods in a try. In other words, there is not much point in catching an exception just to rethrow the same exception unless your throwing a
different exception (i.e. aggregating all unknown exceptions to one of your own application exceptions). So you may have many methods that do not have any try/catch blocks even if you expect an exception. If you would just
rethrow the same exception, why catch it? Let the caller would get the same exception anyway. This assumes you don't have any cleanup code or closing
streams, etc. If you do, they try/finally or try/catch/finally works well. So if you only want to ensure clean up of streams (etc.) you can just use
try/finally. If exception is thrown, your finally will run and the
exception will perk back up the chain so you don't have to rethrow it.
Yes, yes, and yes! A lot of people "insist" on catching exceptions "locally"
instead of letting them bubble up. And it is sometimes very hard to convince
them that they are doing the wrong thing (and this is a source of endless
debates around checked exceptions vs. unchecked exceptions). These people
are caught in the "error code" mindset (Eric Gunnerson introduced this
expression in one of the threads on EH, and I really liked it), they feel
bad if they don't catch exceptions locally (because they still think of them
as error codes that must be tested locally).

In my programming guidelines, there are only two patterns for catch:

* the catch-report-log-resume pattern where I catch all exceptions, report
them to the user in a friendly way, log them, and let the program resume
execution normally. This pattern occurs in a few strategic places (event
loop or event handlers).

* the catch-wrap-rethrow pattern where I wrap a low level exception into a
higher level one, with a higher level message, and I rethrow the higher
level exception. This pattern is usually found in the main entry points of
major modules. The typical example is a resourceManager.LoadResource(string
resourceName) that catches all low level exceptions to rethrow a new
ResourceManagerException("cannot load resource " + resourceName, lowLevelEx)
so that the user gets a precise diagnostics with the resource name, as well
as the low level exception info (without this wrapping, he would only get
the low level info).

If you follow these guidelines, you end up with a lot less exception
handling code, and code that is usually a lot more robust (execution always
resumes in the places where you have decided that it is ok to resume, all
exceptions are logged and logged only once, exceptions carry meaningful info
covering both the low level details of the exception and the high level
context, etc.). And your application logic is clearly separated for the EH
logic because the application logic is written with "normal" constructs
(return values, if/then/else), not with an ugly mixture of normal and EH
constructs.

Also, people are usually afraid to "throw"; I am not! Everytime I encounter
a condition that violates something that should always be true if my code is
correct (for example, if execution ends up in a default switch branch that
should never be reached), I throw an exception (throw new
LogicException("bad switch value " + val)). This is better than letting the
program continue with this abnormal case not handled at all, it forces me to
review the logic and fix the bug instead of letting all sorts of "well, this
strange but if I'm lucky it won't hurt" assumptions invade the code. This
attitude is also very important to get robust code. And I don't have to
worrry about how or where this logic exception will be handled, it is just
another "exceptional" condition, and it will be treated like all the others
and my application will recover cleanly.

Bruno.

--
William Stacey, MVP

"Bruno Jouhier [MVP]" <bj******@club-internet.fr> wrote in message
news:#n**************@TK2MSFTNGP10.phx.gbl...
The big performance hit is when you actually "throw" an exception. If the code unfolds "normally" without throwing any exception you will get a very small performance hit (some instruction that saves the state of the
registers when you enter the try block). I would not worry about it at all and use try/finally (or rather the "using" construct) whenever some resource
needs to be freed (or some invariant restored).

On the other hand, I would recommend that you only use exceptions to deal with "exceptional" situations and that you don't use them as "special
returns" because you will gain on performance and code clarity as well.

Good use of exceptions is a subtle issue. For example, if you have to open a
file that might or might not exist under "normal" conditions, you should
test its presence with File.Exists before opening it instead of opening

it and catching an exception. On the other hand, if the file is supposed to
exist under "normal" conditions (for example because it got created by
another method just before, or because it is installed by your setup and

the
user is not supposed to fool around with it), you should not test it with File.Exists and let the exception handling deal with the "exceptional"

case
where the file does not exist. As you see, this requires a bit of subtlety (is this condition "normal" or "exceptional"?) and some rigor in your
coding, but it is really worth the extra work.

Bruno.
"RepStat" <an*******@discussions.microsoft.com> a écrit dans le message de news:0A**********************************@microsof t.com...
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?

Nov 16 '05 #5

P: n/a
Very Nice! Thanks

--
William Stacey, MVP

"Bruno Jouhier [MVP]" <bj******@club-internet.fr> wrote in message
news:uq**************@TK2MSFTNGP09.phx.gbl...

"William Stacey [MVP]" <st***********@mvps.org> a écrit dans le message de
news:e6**************@TK2MSFTNGP11.phx.gbl...
Good answer!
Also resist the temptation to wrap exceptions in exceptions or wrapping all
your methods in a try. In other words, there is not much point in

catching
an exception just to rethrow the same exception unless your throwing a
different exception (i.e. aggregating all unknown exceptions to one of

your
own application exceptions). So you may have many methods that do not

have
any try/catch blocks even if you expect an exception. If you would just
rethrow the same exception, why catch it? Let the caller would get the

same
exception anyway. This assumes you don't have any cleanup code or closing
streams, etc. If you do, they try/finally or try/catch/finally works

well.
So if you only want to ensure clean up of streams (etc.) you can just use try/finally. If exception is thrown, your finally will run and the
exception will perk back up the chain so you don't have to rethrow it.


Yes, yes, and yes! A lot of people "insist" on catching exceptions

"locally" instead of letting them bubble up. And it is sometimes very hard to convince them that they are doing the wrong thing (and this is a source of endless
debates around checked exceptions vs. unchecked exceptions). These people
are caught in the "error code" mindset (Eric Gunnerson introduced this
expression in one of the threads on EH, and I really liked it), they feel
bad if they don't catch exceptions locally (because they still think of them as error codes that must be tested locally).

In my programming guidelines, there are only two patterns for catch:

* the catch-report-log-resume pattern where I catch all exceptions, report
them to the user in a friendly way, log them, and let the program resume
execution normally. This pattern occurs in a few strategic places (event
loop or event handlers).

* the catch-wrap-rethrow pattern where I wrap a low level exception into a
higher level one, with a higher level message, and I rethrow the higher
level exception. This pattern is usually found in the main entry points of
major modules. The typical example is a resourceManager.LoadResource(string resourceName) that catches all low level exceptions to rethrow a new
ResourceManagerException("cannot load resource " + resourceName, lowLevelEx) so that the user gets a precise diagnostics with the resource name, as well as the low level exception info (without this wrapping, he would only get
the low level info).

If you follow these guidelines, you end up with a lot less exception
handling code, and code that is usually a lot more robust (execution always resumes in the places where you have decided that it is ok to resume, all
exceptions are logged and logged only once, exceptions carry meaningful info covering both the low level details of the exception and the high level
context, etc.). And your application logic is clearly separated for the EH
logic because the application logic is written with "normal" constructs
(return values, if/then/else), not with an ugly mixture of normal and EH
constructs.

Also, people are usually afraid to "throw"; I am not! Everytime I encounter a condition that violates something that should always be true if my code is correct (for example, if execution ends up in a default switch branch that
should never be reached), I throw an exception (throw new
LogicException("bad switch value " + val)). This is better than letting the program continue with this abnormal case not handled at all, it forces me to review the logic and fix the bug instead of letting all sorts of "well, this strange but if I'm lucky it won't hurt" assumptions invade the code. This
attitude is also very important to get robust code. And I don't have to
worrry about how or where this logic exception will be handled, it is just
another "exceptional" condition, and it will be treated like all the others and my application will recover cleanly.

Bruno.

--
William Stacey, MVP

"Bruno Jouhier [MVP]" <bj******@club-internet.fr> wrote in message
news:#n**************@TK2MSFTNGP10.phx.gbl...
The big performance hit is when you actually "throw" an exception. If the code unfolds "normally" without throwing any exception you will get a very small performance hit (some instruction that saves the state of the
registers when you enter the try block). I would not worry about it at all and use try/finally (or rather the "using" construct) whenever some resource
needs to be freed (or some invariant restored).

On the other hand, I would recommend that you only use exceptions to deal with "exceptional" situations and that you don't use them as "special
returns" because you will gain on performance and code clarity as well.
Good use of exceptions is a subtle issue. For example, if you have to open
a
file that might or might not exist under "normal" conditions, you should test its presence with File.Exists before opening it instead of opening it and catching an exception. On the other hand, if the file is supposed
to exist under "normal" conditions (for example because it got created by
another method just before, or because it is installed by your setup and the
user is not supposed to fool around with it), you should not test it
with File.Exists and let the exception handling deal with the "exceptional"

case
where the file does not exist. As you see, this requires a bit of subtlety (is this condition "normal" or "exceptional"?) and some rigor in your
coding, but it is really worth the extra work.

Bruno.
"RepStat" <an*******@discussions.microsoft.com> a écrit dans le
message de news:0A**********************************@microsof t.com...
> 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?



Nov 16 '05 #6

P: n/a
From what I've read, having numerous try/catch blocks doesn't affect
performance. As you mentioned, relying on exception being thrown as
part of your mainstream logic does indeed have a performance hit.

But any experienced developer knows that catching exceptions as part
of mainstream logic is pretty silly anyway - a bad idea even if there
wasn't a performance hit.

Nov 16 '05 #7

This discussion thread is closed

Replies have been disabled for this discussion.