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..fin ally block, just in case there might be an exception? i.e. is it ok performance-wise to pepper pieces of code with try..catch..fin ally blocks that must be robust, in order that cleanup can be done correctly should there be an exception? 6 2829
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.co m
"RepStat" <an*******@disc ussions.microso ft.com> wrote in message
news:0A******** *************** ***********@mic rosoft.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..fin ally block, just in case there
might be an exception? i.e. is it ok performance-wise to pepper pieces of
code with try..catch..fin ally blocks that must be robust, in order that
cleanup can be done correctly should there be an exception?
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 "exceptiona l" 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 "exceptiona l" case
where the file does not exist. As you see, this requires a bit of subtlety
(is this condition "normal" or "exceptiona l"?) and some rigor in your
coding, but it is really worth the extra work.
Bruno.
"RepStat" <an*******@disc ussions.microso ft.com> a écrit dans le message de
news:0A******** *************** ***********@mic rosoft.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..fin ally block, just in case there
might be an exception? i.e. is it ok performance-wise to pepper pieces of
code with try..catch..fin ally blocks that must be robust, in order that
cleanup can be done correctly should there be an exception?
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******@clu b-internet.fr> wrote in message
news:#n******** ******@TK2MSFTN GP10.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 "exceptiona l" 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 "exceptiona l"
case where the file does not exist. As you see, this requires a bit of subtlety (is this condition "normal" or "exceptiona l"?) and some rigor in your coding, but it is really worth the extra work.
Bruno.
"RepStat" <an*******@disc ussions.microso ft.com> a écrit dans le message de news:0A******** *************** ***********@mic rosoft.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..fin ally block, just in case
there might be an exception? i.e. is it ok performance-wise to pepper pieces of code with try..catch..fin ally blocks that must be robust, in order that cleanup can be done correctly should there be an exception?
"William Stacey [MVP]" <st***********@ mvps.org> a écrit dans le message de
news:e6******** ******@TK2MSFTN GP11.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(s tring
resourceName) that catches all low level exceptions to rethrow a new
ResourceManager Exception("cann ot 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 "exceptiona l" condition, and it will be treated like all the others
and my application will recover cleanly.
Bruno. -- William Stacey, MVP
"Bruno Jouhier [MVP]" <bj******@clu b-internet.fr> wrote in message news:#n******** ******@TK2MSFTN GP10.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 "exceptiona l" 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 "exceptiona l" case where the file does not exist. As you see, this requires a bit of
subtlety (is this condition "normal" or "exceptiona l"?) and some rigor in your coding, but it is really worth the extra work.
Bruno.
"RepStat" <an*******@disc ussions.microso ft.com> a écrit dans le message
de news:0A******** *************** ***********@mic rosoft.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..fin ally block, just in case there might be an exception? i.e. is it ok performance-wise to pepper pieces
of code with try..catch..fin ally blocks that must be robust, in order that cleanup can be done correctly should there be an exception?
Very Nice! Thanks
--
William Stacey, MVP
"Bruno Jouhier [MVP]" <bj******@clu b-internet.fr> wrote in message
news:uq******** ******@TK2MSFTN GP09.phx.gbl... "William Stacey [MVP]" <st***********@ mvps.org> a écrit dans le message de news:e6******** ******@TK2MSFTN GP11.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(s tring resourceName) that catches all low level exceptions to rethrow a new ResourceManager Exception("cann ot 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 "exceptiona l" condition, and it will be treated like all the
others and my application will recover cleanly.
Bruno.
-- William Stacey, MVP
"Bruno Jouhier [MVP]" <bj******@clu b-internet.fr> wrote in message news:#n******** ******@TK2MSFTN GP10.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 "exceptiona l" 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 "exceptiona l" case where the file does not exist. As you see, this requires a bit of subtlety (is this condition "normal" or "exceptiona l"?) and some rigor in your coding, but it is really worth the extra work.
Bruno.
"RepStat" <an*******@disc ussions.microso ft.com> a écrit dans le
message de news:0A******** *************** ***********@mic rosoft.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..fin ally block, just in case there might be an exception? i.e. is it ok performance-wise to pepper pieces of code with try..catch..fin ally blocks that must be robust, in order
that cleanup can be done correctly should there be an exception?
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. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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...
|
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
|
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 former, i have a few questions that need to be
answered.
1) What about functions that need to return a value regardless of the
error. How can they also return an error code unless the function has
"output" parameters. This seems messy and...
|
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 find myself convinced
that exceptions are a better mechanism, for example because
constructors and operators can't return errors, and code that doesn't
need to handle/translate/recover in the face of errors, but can just
propagate the error is...
|
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 presented that says
"Use conventional error-handling techniques rather than exception
handling for straightforward local error processing in which a program
is easily able to deal with its own errors."
By "conventional error-handling," I believe...
| |
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 improved code readability and performance.
Consider an application that must eliminate duplicates in a list.
using system.collections;
|
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 or
that it's not alphabetic when it's supposed to be numeric is arguably
best left to the business tier code on the server where there is
access to other data.
My questions, is what's the best way to communicate complicated error
checking...
|
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 public
member with a return type that is derived from System.Exception? I
understand the importance of having clean, concise code that follows
widely-accepted patterns and practices, but in this case, I find it
hard to blindly follow a standard...
|
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 fcn is a boolean
and there are certain places within the inner functions where it may
become apparent that the return value is false. In this case I'd like
to halt the computation immediately and return false.
My current approach is to have...
|
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...
|
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...
| |
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...
|
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...
|
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();...
|
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...
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |