Nice Subprocedures with RPG ON-EXIT
IBM is adding all kinds of new tweaks to RPG with each new release of IBM i. RPG ON-EXIT is a great example of a neat tweak to the RPG programming language.
Last year, IBM quietly introduced a rather neat new function called “ON-EXIT” to our sub procedures in RPG.
RPG ON-EXIT is a nice structured way of storing procedure house keeping and/or error catching.
ON-EXIT is available if you are running IBM i V7.2 or higher:
The ILE RPG compiler is enhanced with a new ON-EXIT opcode which begins the “ON-EXIT” section containing code to be run whenever a procedure ends, either normally or abnormally.
So, if you have code that you always want to run at the end of a procedure you can just put that in the ON-EXIT section.
So how does ON-EXIT work?
The ON-EXIT operation code begins the ON-EXIT section. The ON-EXIT section contains code that runs every time that the procedure ends, whether it ends normally or abnormally. The ON-EXIT section runs under the following conditions:
- The procedure reaches the end of the main part of the procedure.
- The procedure reaches a RETURN operation.
- The procedure ends with an unhandled exception.
- The procedure is canceled, due to the end of the job or subsystem, or due to an exception message being sent to a procedure higher in the call stack.
By placing your clean-up code, such as deleting temporary files and deallocating heap storage, in the ON-EXIT section, you ensure that it is always run, even if your procedure ends with an unhandled exception, or if it is canceled.
Extended Factor 2 contains an optional indicator variable that indicates whether the procedure ended normally or abnormally. If the procedure returned normally, the indicator is set to *OFF. If the procedure ended with an unhandled exception or if the procedure was canceled for any other reason, the indicator is set to *ON.
The ON-EXIT section is coded at the end of the subprocedure, following any subroutines.
All variables and files defined in the procedure are available in the ON-EXIT section.
I can already think about using ON-EXIT something like this:
dcl-proc myproc; dcl-s OhBuggerIcrashed ind inz(*off); dcl-s success ind inz(*off); Open fileName; doStuff = things * widgets / shoeshize; filename = crtTempFile(); // we could also handle errors this way monitor; dosomelogic(); on-error; OhBuggerIcrashed = *on; return; endif; ... // do lots of subprocedure logic stuff success = *on; return; on-exit OhBuggerIcrashed; // then we could have some logic added around the "myProcFinished" indicator if success; dltTempFile (filename); endif; // "OhBuggerIcrashed" is set *ON if the on-exit is invoked abnormally // (so it acts sort of like a *PSSR capture) if OhBuggerIcrashed; reportProblem (); endif; // any housekeeping that we want to do if we finished cleanly or not Close fileName; end-proc;
That’s only rough code but it should give you the idea…