ClearAll[f, fc]
f::zero = "x is zero.";
(* compiled part *)
fc =
Compile[{{x, _Complex}},
(* First part of the code; can be anything
.
.
*)
If[x == 0, (* Error test*)
{0, 0}, (* Error response, first part is status, second part is dummy *)
{1, x^2} (* Normal response, first part is status, second part actual result *)
]
];
(* wrapper part *)
f[x_] := With[{res = fc[x]},
If[Chop[res[[1]]] == 0, (* check status *)
Message[f::zero]; $Failed, (* error *)
res[[2]] (* normal result *)
]]
f[0]
f[1]
(* 1. + 0. I *)
or with MichaelE2's suggestion:
ClearAll[f, fc]
f::zero = "x is zero.";
fc =
Compile[{{x, _Complex}},
(* First part of the code *)
If[x == 0, (* Error test*)
{},(* Error response, empty list *)
{x^2} (* Normal response, list with result *)
]
];
f[x_] := With[{res = fc[x]}, If[res == {}, Message[f::zero]; $Failed, First@res]]