Some additional information you may find helpful. Consider this:
In[26]:= f1 = Function[v, Do[If[v[[i]] < 0, Return[v[[i]]]], {i, 1, Length[v]}]; last = 1;]; In[27]:= last Out[27]= last In[28]:= f1[{-1, 2, 3}] In[29]:= last Out[29]= 1
Despite the fact that the function had to return to the first element that it received for last = 1, Therefore, as others noted, Return does not work. This will not be fixed as too much code depends on this behavior.
Now you can use:
In[30]:= f2 = Function[v, Module[{}, Do[If[v[[i]] < 0, Return[v[[i]], Module]], {i, 1, Length[v]}]; last2 = 1;]]; In[31]:= f2[{-1, 2, 3}] Out[31]= -1 In[32]:= last2 Out[32]= last2
Which behaves as expected. Unfortunately, however,
In[33]:= c1 = Compile[{{v, _Integer, 1}}, Module[{}, Do[If[v[[i]] < 0, Return[v[[i]], Module]], {i, 1, Length[v]}]; ] ];
will not compile.
Here's how to do it.
In[137]:= c1=Compile[{{v,_Integer,1}}, Module[{res=1}, Do[If[v[[i]]<0,res=v[[i]];Break[]],{i,1,Length[v]}]; If[res==1,Internal`CompileError[]]; res ] ,"RuntimeOptions"->{"RuntimeErrorHandler"->Function[Null]}] In[140]:= c1[{1,2,3,1}] In[141]:= c1[{1,2,3,-1}] Out[141]= -1
Check the output.
In[139]:= CompilePrint[c1]
Some additional notes: "RuntimeErrorHandler" โ The [Null] function is a function! Think about it for a second. You can thow message something!
So something like this works.
cfquietfail = Compile[{{x, _Real, 1}}, Exp[x], "RuntimeOptions" -> {"WarningMessages" -> False, "RuntimeErrorHandler" -> Function[Message[MyFunctionName::"I can complain here!"]; Throw[$Failed]]}]; Catch[ cfquietfail[{1000.}]]
Hope this is helpful.