tags:

views:

234

answers:

9

Possible Duplicate:
How slow are .NET exceptions?

I've been reading all over the place (including here) about when exception should / shouldn't be used. I now want to change my code that would throw to make the method return false and handle it like that, but my question is: Is it the throwing or try..catch-ing that can hinder performance...? What I mean is, would this be acceptable:


bool method someMmethod()
{
    try
    {    
        // ...Do something
    catch (Exception ex) // Don't care too much what at the moment...
    {
        // Output error
        // Return false
    }
    return true // No errors

Or would there be a better way to do it? (I'm bloody sick of seeing "Unhandled exception..." LOL!)

+4  A: 

Ask yourself the following question: Is the exception exceptional?

  • If this can happen in normal program flow, for example, a failure to parse a number typed by the user, don't use an exception.
  • If this should not normally happen, but rather signifies a problem outside the program's control, such as a missing file, use an exception.
Thomas
A: 

Performance-wise, you wouldn't see any difference. It's a micro-optimization to leave out try-catch because it's hindering performance.

However... That said, I'm not convinced your motives to do so are entirely valid. If the function that throws is your own, then I guess it's throwing for a reason and catching the exception might conceal an important error.

Johann Gerell
Thanks peeps, but what I meant is, is it OK to use the try..catch but NOT throw (but rather return false and handle it in the caller).The reason I'd want to catch it is to give MYSELF info during dubugging (but I have a flag I can set to limit output in 'production')
Richard
Also, wouldn't I get the info (from 'ex' in the above code).It'll probaly only happen because someone forgets to check array boundries (but not me, honestly!)
Richard
@Richard: Yes, it's ok. I typically do that myself in `Try...` helper functions that wraps something that might throw. But you need to understand the full consequences and not just eat any thrown exception without knowing why it happened.
Johann Gerell
A: 

I often heard that Exceptions are slow when thrown the first time, as some module or whatever has to be loaded. But, as Blorgbeard said, Exceptions are for exceptional cases. It shouldn't matter.

eWolf
+1  A: 

Exceptions are for exceptional cases. If your // ...Do something is throwing exceptions during normal flow, fix it.

Ax
A: 

Putting try...catch around code will not really hinder performance, code that may fail should always have a try...catch around it.

However, you should always avoid exceptions being thrown in the first place because these significantly hit performance.

Never throw an exception unless it is truly exceptional!

Your returning false implies a pattern similar to that used with the TryParse() method.

David Neale
+2  A: 

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).

Adam Robinson
+1  A: 

If you have a try/catch block and this block does not throw an exception, it runs at the same speed as if you didn't have the try/catch block wrapping it. It's only when an exception is actually thrown does performance go down, but if you are using exceptions as designed, it doesn't matter as you are now in an exceptional situation. Exceptions should not be used for control flow.

Matt Greer
A: 

Its just that you shouldn't allow the exception to raise for logic i.e. you shouldn't leave the catch block with responsibility or returning false always. Simply putting, it should not be used for logic.

For example, when you can check for null and return false, you should not call method on null to have a NullReferenceException and let the catch block return false.

Ismail
A: 

Its also a common misconception of developers to think catching Exception is a good idea.

If Exception happened to be a StackOverflowException or an OutOfMemoryException you probably wouldnt want your application to continue in these cases.

Regarding performance, using exceptions to control program flow would hurt performance significant, partly because each time an exception is thrown the clr must walk the stack to find a catch statement (called stack unwinding)

The TryXXX pattern is one way of attempting to perform some action without an exception being thrown.

antinutrino