Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern: Elegant way to do something upon function exit?

I have a function with logic that looks like this:

doStuff1()
try:
    doStuff2()
except type1:
    error1()
    return endstuff()
except type2:
    error2()
    return endstuff()
except:
    error3()
    return endstuff()

if doStuff3():
    error4()
    return endstuff()

doStuff4()
return endstuff()

As you can see, endstuff() is done on every possible exit to the function. As it is now, endstuff() is actually 2 lines of code, and I recently had to add a third one to all possible exits. Is there any more elegant way to organize this code? I can't just use a finally, as it's not always the case that an exception is thrown.

like image 346
Claudiu Avatar asked Nov 22 '25 04:11

Claudiu


1 Answers

You can use a finally even if no exception is thrown and AFAIK this is the most elegant way to do what you want.

like image 200
Otávio Décio Avatar answered Nov 23 '25 21:11

Otávio Décio