Related discussion is here. All of the clauses of conditional expressions are evaluated even if the conditions are false. It is a matter of taste to decide whether this is a bug or not. To me, it seems like a very strange feature, requiring additional processing.
We can see that if we look closer at the Michael E2's example:
ClearAll[f];
f[x_] := Piecewise[{{1/(x + 2), x <= 0}, {Sqrt[1/(x + 1)], 0 < x <= 1}}, x]
Plot[f[x], {x, -3, 0}]

Note the discontinuity of the upper curve at x = -1
, which is an indication that MMA is evaluating all expressions of Piecewise
before rendering.
We can wrap the function that causes this in Unevaluated
to prevent such behavior.
ClearAll[f];
f[x_] := Piecewise[{{1/(x + 2), x <= 0}, {Unevaluated@Sqrt[1/(x + 1)], 0 < x <= 1}}, x]
Plot[f[x], {x, -3, 0}]
No errors

The same fix applies to the OP example:
f[x_] = Piecewise[{{1/(Cos[x^2 + 2]), x <= 0}, {Unevaluated[Sqrt[x^2/(x + 1)]], 0 < x <= 1}, {(x^2 - 2 x)/Abs[2 - x], True}}];
Plot[f[x], {x, -3, 3}]
No errors

What seems much more troublesome is the workaround that Bob Hanlon discovered and which does nothing more than taking 1 in the numerator out of the square root. In other words, there is still a possibility for the denominator to become 0 when evaluated unconditionally (at x == -1
), so we should expect the same error, but for some reason there is no error now. This is a bug for sure, as it is at least inconsistent and therefore needs to be fixed.
g[x_] := Piecewise[{{1/(x + 2), x <= 0}, {1/Sqrt[(x + 1)], 0 < x <= 1}}, x]
Plot[g[x], {x, -3, 0}]
No errors!
For the sake of completeness, the mechanism that is probably glitching here is Exclusions
, as Michael E2's example can also be fixed by explicitly indicating types of checks we want:
f[x_] := Piecewise[{{1/(x + 2), x <= 0}, {Sqrt[1/(x + 1)], 0 < x <= 1}}, x]
Plot[f[x], {x, -3, 0}, Exclusions -> "Singularities"]
No errors
This, however, wouldn't work nicely for the OP example, as it has more than one type of exclusions, so we need to use one of the alternative solutions in this post or thread.
Quiet[]
? $\endgroup$Sqrt
expression. I thinkx = -1.
is being plugged into it. Why?, you might ask. Well, it does some symbolic analysis to determine discontinuities in the graph. It's probably a bug, but I haven't been able to track it down yet. You can useQuiet
if it's annoying. $\endgroup$