# How to know when FindRoot[] fails to find a solution

My problem is very simple. Assume you have this piece of code :

FindRoot[{x^2 + 1 == 0}, {x, -1, 1}]


Now, this code returns

FindRoot::cvmit: Failed to converge to the requested accuracy or precision within 100 iterations.
{x -> -1.}


Which is as expected since the equation has no real root. Now my question is, how can I get the fact that FindRoot failed in a variable ? Say I want to display a message "Failed search", when FindRoot fails for whatever reason, how do I collect the fact that the function failed ? I was looking into Catch[], but it seems that no exception is thrown.

• Commented Dec 10, 2020 at 20:18
• Works great, thanks ! Commented Dec 10, 2020 at 20:21
• FindRoot can find complex roots if you tell it to look in the complex plane, e.g., FindRoot[{x^2 + 1 == 0}, {x, -1 + I, 1 + I}] evaluates to {x -> 1.16068*10^-19 + 1. I} Commented Dec 11, 2020 at 2:18

To expand @Carl's comment:

res = Check[
FindRoot[{x^2 + 1 == 0}, {x, -1, 1}], $$Failed[Evaluate@$$MessageList]]


FindRoot::cvmit: Failed to converge to the requested accuracy or precision within 100 iterations.

(*  $Failed[{FindRoot::cvmit}] *)  Some ways to query the result res FreeQ[res,$Failed]   (* True => success *)

(*  False  *)

FreeQ[res, "cvmit"]   (* False => "cvmit" message occurred *)

(*  False  *)

FreeQ[res, FindRoot]  (* False => message(s) from FindRoot occurred *)

(*  False  *)


The structure of res, which is obscured by the standard output form:

FullForm[res]

(*  \$Failed[List[HoldForm[MessageName[FindRoot, "cvmit"]]]]  *)