Exit is used to exit a method at any point in the method. A Method normally process statements as you would expect, from top to bottom and when the latter is reached it exits back to the caller. This does not mean that all statements are processed once. Statements can be:
- bypassed (if, iif, case of)
- processed multiple times (Loops)
If you need to leave the method from anywhere within it, use the exit command, e.g.:
method MyForm1.SaveProject; begin if not Assigned(fProject) then exit; // code follows here end;
Although you can provide multiple exits to a method, it is good practice to keep them to a minimum - maintenance quality and robustness is greatly improved. The above example illustrates a good use of exit - after initial validation checks. You could replace by if/then/else but it makes the method harder to read.
If your method is a function (i.e. returns a Result), you can pass this back as an exit parameter, which can be extremely convenient. Thus, we can do this for the example above as follows:
method MyForm1.SaveProject: Boolean; begin if not Assigned(fProject) then exit false; Result := True; // code follows here end;
From the Spring 2010 release onwards, it's possible to exit to a method - see Tail Calls.
Exiting from a parallel loop
It's not possible to exit the function from within a parallel loop as the body of the loop is executed in the context of another method.