If your question is whether or not the presence of a try...catch
block will affect performance, then no.
If your question is whether there is a performance hit in using an exception-based model rather than a return value model, then yes, there is. Having a function like this:
public void DoWork()
{
if(something) throw new Exception(...);
}
Is not going to perform as well under error conditions as a function like this:
public bool DoWork()
{
if(something) return false;
return true;
}
Exceptions have to unwind the stack and kick you out to the nearest catch
block in order to work, so there's overhead involved in that. It's simpler to return a status value, but it's also a more choppy interface to deal with when exceptions are not the rule.
However, that isn't the point. If you're writing code where exceptions are the rule, then you have a problem. Exceptions should be used in...exceptional...conditions, such as when you encounter a condition that you could not account for in code.
Consider the types like int
and DateTime
. These types provide (among others) two different functions for converting string values into corresponding int
and DateTime
values: Parse
and TryParse
. Parse
uses the exception model, since it's assuming at that point that you'll be passing it a well-formed integer value, so if it gets something else, that's an exceptional condition. TryParse
, on the other hand, is designed for when you are not sure about the format of the string, so it uses the return value model (along with an out
parameter in order to get the actual converted value).