How to exit a script on error?


I’m working on some very long Rhinoscripts which automate madCAM toolpath generation.

I’d like to include error checking and have my scripts stop automatically when the required objects or layers don’t exist in the current Rhino document.

I’ve searched extensively and can only find the Exit Sub command but I need an “Exit Script” command.

Any tips would be greatly appreciated!



I suppose I could change all of my Sub procedures into Function procedures and have them return a Boolean success/fail value to the Main procedure, then surround each function call with an if/then conditional which would exit Main on an error.

But this seems a bit clunky. Is there not an easier way to exit a Rhinoscript?


Hi Leo,

Typically your script structure would be like this:

Call Main()
Sub Main()
    [do something]
   If <condition not met> then Exit Sub
End Sub

So only “Main” would be called and the errors/exiting would be checked there. All other Functions or Subs should communicate the condition status via some variable to the Main Sub so you can exit form there.

Not sure if this is related but you may check the special function in RhinoScript OnCancel for some cleanup possibilities while error happens or user cancels the script.




Thanks very much for your reply Jarek.

So since Sub procedures do not return values then I just need to use Functions instead, does that sound right?

Thanks for your simple example code. I think I’m on the right track :slight_smile:



You can actually use sub that you feed with a variable as a reference:

Sub Action(ByRef blnSuccess)
   if <failure> then blnSuccess=False
End Sub

When you use ByRef, the original variable passed is modified in the calling scope. So you can communicate success or failure of Sub with the main Sub.

See more here: