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

Exceptions and performance hit

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
6 2804
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
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
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

"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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

26
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...
7
by: Michael Andersson | last post by:
Hi! Does the use of exception handling induce a performance penalty during the execution of non exception handling code? Regards, /Michael
5
by: Mark Oueis | last post by:
I've been struggling with this question for a while. What is better design? To design functions to return error codes when an error occures, or to have them throw exceptions. If you chose the...
8
by: Shane Groff | last post by:
I know this is a recurring discussion (I've spent the last 3 days reading through threads on the topic), but I feel compelled to start it up again. After reading through the existing threads, I...
59
by: kk_oop | last post by:
Hi. I wanted to use exceptions to handle error conditions in my code. I think doing that is useful, as it helps to separate "go" paths from error paths. However, a coding guideline has been...
9
by: Alvin Bruney [MVP] | last post by:
Exceptions must not be used to control program flow. I intend to show that this statement is flawed. In some instances, exceptions may be used to control program flow in ways that can lead to...
2
by: headware | last post by:
I realize that when making a web application, performing input validation in the browser is good because it prevents postbacks. However, input checking that goes beyond making sure a value exists...
14
by: dcassar | last post by:
I have had a lively discussion with some coworkers and decided to get some general feedback on an issue that I could find very little guidance on. Why is it considered bad practice to define a...
40
by: Mark P | last post by:
I'm implementing an algorithm and the computational flow is a somewhat deep. That is, fcn A makes many calls to fcn B which makes many calls to fcn C, and so on. The return value of the outermost...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
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: 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
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...

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.