Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(); 
}
like image 483
ChuckNeuros Avatar asked Aug 26 '11 15:08

ChuckNeuros


2 Answers

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.

like image 64
abatishchev Avatar answered Oct 11 '22 10:10

abatishchev


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?

like image 34
Tim B James Avatar answered Oct 11 '22 10:10

Tim B James