You might consider making a "helper" grade item, that you would use in your formula instead of `final`. The helper grade item would be hidden, and set to have a weight of 0 (so that it does not appear to students, and does not contribute to their overall grade). That grade item formula could use a clever combination of ROUND, FLOOR, CEILING, MIN, MAX, 1, and/or 0, to basically return the `midterm` value of the `final` is 0, or otherwise return the `final` value. Then, the non-weighted or weighted average of `midterm` with itself, is exactly `midterm`.
(of course, you do not necessarily need to make it a separate grade item, you could just repeatedly substitute the helper calculation into your formula. However, if you're going to repeat a calculation, I would prefer to put it somewhere else.)
Notice the problem with that, though: based on the way calculations work with empty grades, there is no way to distinguish an empty grade, from a 0 grade. So, the resulting `exams` grade will be wrong if a student legitimately scores a 0 on the final. The workaround would be that you just manually override the grade for anyone who scores a 0 (and outside Moodle, encourage them to score higher than a 0 in the future, at least for the sake of your calculations ).
If you can guarantee that all students' grades are non-zero, then the formulae in this thread (or this thread) might suggest a way to count if a grade exists or not. That might allow you to completely forgo all this "helper" stuff.
Do either of those options sound helpful?