ChuckNeuros
ChuckNeuros

Reputation: 147

Return in try & catch versus return in finally?

Is either one of these risky? Is one better? Or is it one of those things you print out and throw a dart at to decide?

I want to do this now that I understand how finally works:

try { 
    stuff that changes something... 
}
catch (System.Exception ex) { 
    something.worked = false; 
    something.err = ex.Message; 
}
finally { 
    stuff.close();
    return something; 
}

But I've seen:

try { 
    stuff that changes something...
    return something; 
}
catch (System.Exception ex) { 
    something.worked = false; 
    something.err = ex.Message; 
    return something; 
}
finally { 
    stuff.close(); 
}

Upvotes: 13

Views: 23176

Answers (3)

Tim B James
Tim B James

Reputation: 20364

Personally I would do neither and would use


try { 
    stuff that changes something... 
}
catch (System.Exception ex) { 
    something.worked = false; 
    something.err = ex.Message; 
}
finally { 
    stuff.close();    
}
return something; 

Also in the finally statement, check that you need to close/dispose of objects as they might have never been opened/set if they have failed.

Also see here Is it bad practice to return from within a try catch finally block?

Upvotes: 18

abatishchev
abatishchev

Reputation: 100348

You can't return from finally. You will get compiler error:

Control cannot leave the body of a finally clause


If target class implements IDisposable then I would do next:

using (stuff s = new stuff())
{
    return stuff;
}

or

using (stuff s = new stuff())
{
    try
    {
        // do stuff
        return stuff;
    }
    catch (Exception ex)
    {
        // do logging or another stuff
        return something;
    }
}

will call Dispose() for you if that will be required/possible.

Upvotes: 20

Stephan
Stephan

Reputation: 4247

There is no risk in the second approach. But it allows you to return different values in case of exceptions.

Upvotes: 0

Related Questions