开发者

Return in try & catch versus return in finally?

开发者 https://www.devze.com 2023-03-30 20:25 出处:网络
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?

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.Except开发者_如何学Pythonion 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(); 
}


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.


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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消