29
Fri, Nov
0 New Articles

Clean Up Your Mess! With RPG’s On-Exit

RPG
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

One of my favorite new additions to RPG is the On-Exit opcode. Unfortunately, it seems to have flown under the radar of many RPG developers.

In a previous article on updating your RPG skills, I discussed using subprocedures and using linear-main programs. Using subprocedures gives your application much more flexibility and stability if done properly. Locally scoped variables and files insulate your code from outside interference. The ability to use return values allows your subprocedures to be used directly in calculations or as parameters for other subprocedures or programs.

One newer feature of subprocedures that many developers seem to have overlooked is the On-Exit opcode. This opcode is possibly my favorite new addition to RPG. Not only is it simple to use, but it is also foolproof.

What Is On-Exit?

The On-Exit opcode allows you, as a developer, to designate code to be run when the subprocedure ends. That doesn’t sound very useful at first glance. Why not just put the code at the end of the subprocedure? Well, a subprocedure doesn’t always execute to the last line. What if you code a return opcode somewhere in the subprocedure? On-Exit will still run, no matter where the procedure returns. What if the procedure ends abnormally due to an unhandled exception? On-Exit will still run even when the procedure ends due to error. What if the program ends due to the subsystem ending? Yep, On-Exit will still run.

Now it should be clearer why this opcode can be so useful.

What Do I Need to Use On-Exit?

First, you must be on IBM i 7.2 or greater. If you are running 7.1, it is time to start planning your upgrade anyway. End of support for IBM i 7.1 is April 2018. Next, you will need some PTFs:

  • 7.1—SI62949 and SI62955 or DB2 PTF group SF99702 Level 14
  • 7.2—SI62950 and SI62957 and SI62965 or DB2 PTF group SF99703 Level 3

You will also want to be sure to be on at least RDi 9.5.1 for the syntax checker to recognize On-Exit. Before someone asks, no, the syntax checker in SEU will not be updated for this opcode. SEU was stabilized at IBM i 6.1. It’s dead.

How Do I Use It?

Using On-Exit could not be simpler. Have a look for yourself.

**Free

Dcl-Proc MyProcedure;

Dcl-S Abnormal_End Ind;

// Do Subprocedure Stuff

On-Exit Abnormal_End;

If Abnormal_End;

   // Do Stuff

Else;

   // Do Different Stuff

EndIf;

End-Proc;

The On-Exit section must come after all other code for your subprocedure. You may specify an indicator in the factor 2 position. This indicator will be set to *on if the procedure ends abnormally. I recommend specifying the indicator every time On-Exit is used. For me, doing so reminds me to think about what I should do if the subprocedure crashes or is canceled. Even if I don’t want to do special processing in case of an abnormal end, having the indicator there costs me nothing but a tiny amount of allocated storage.

Now that we know how to implement On-Exit, what are the use cases for implementing it?

Cleaning Up After Ourselves

On-Exit is great for making sure we clean up things when a process is finished. It allows us to put in code to handle the cleanup and know that no matter what the next developer may do to the logic, the code to tidy things up will run.

For example, let’s say we are dynamically allocating storage in our code.

**Free

Dcl-Proc MyProcedure;

Dcl-S Abnormal_End Ind;

Dcl-S My_Storage Pointer;

My_Storage = %Alloc(300);

My_Storage = %ReAlloc(My_Storage : 500);

On-Exit Abnormal_End;

If Abnormal_End;

   // Do Stuff

EndIf;

DeAlloc(n) My_Storage;

End-Proc;

This example is obviously oversimplified, but it demonstrates the point. By putting my DEALLOC operation in the On-Exit section of my subprocedure, I know that, no matter what happens in the subprocedure, the storage I have allocated will be freed up. Since I did not condition the deallocation, it will run when the subprocedure ends normally or abnormally.

What if we are creating a temporary stream file in the IFS? Maybe we are building it and FTPing it somewhere.

**Free

Dcl-Proc MyProcedure;

Dcl-S Abnormal_End Ind;

Dcl-S My_Temp_File Int(10);

My_Temp_File = open('/path/my.file' : flags : mode);

// Do Stuff with stream file

On-Exit Abnormal_End;

If Abnormal_End;

   // Do Stuff

EndIf;

CallP close(My_Temp_File);

CallP unlink('/path/my.file');

End-Proc;

Again, the code has been overly simplified. By putting in the close() and unlink() calls to close the file and delete it, I know that the temp file will not hang around after the subprocedure ends. Sure, I may need to close the file in the actual logic of the subprocedure if I need to FTP it, for example. Having the extra close() in the On-Exit certainly won’t hurt anything. If this is a high-volume process and you are worried about the extra overhead of running close() multiple times, just condition it using the Abnormal_End indicator.

Generic Error Logging

While you should use a monitor block to catch any errors you expect to be possible, On-Exit can be useful for gathering information about errors you didn’t expect.

**Free

Dcl-Proc MyProcedure;

Dcl-S Abnormal_End Ind;

// Do Stuff

On-Exit Abnormal_End;

If Abnormal_End;

   Log_Error_Info();

EndIf;

// Do Cleanup Stuff

End-Proc;

Again, this is not a replacement for proper error monitoring in your code. Use Monitor where appropriate. However, when an unexpected error occurs, having the On-Exit code write pertinent information to a log file for later review is a good idea. Things to think about logging would be the user name, error code, parameter values, current timestamp, call stack, or anything else you deem useful. This can make recreating an error and debugging much easier. You also don’t have to depend on an end user to actually report the error and tell you how it happened. I can’t count how many times I have heard from an end user, “Oh, that error happens all the time. We just take a C until we get back to the menu.”

Overriding a Return Value

Another interesting capability of On-Exit is the ability to change the value returned by the subprocedure.

**Free

Dcl-Proc MyProcedure;

Dcl-Pi *n Int(10);

   MyParm Zoned(5:2);

End-Pi;

Dcl-S Abnormal_End Ind;

Dcl-S My_Result Zoned(5:2);

My_Result = MyParm - 5;

Return My_Result;

On-Exit Abnormal_End;

If Abnormal_End;

   // Do Stuff

EndIf;

If My_Result < 0;

   Return 0;

EndIf;

End-Proc;

In this example, we are performing a calculation using a value passed in as a parameter. Let’s say that our business rules dictate that this calculated value can never be negative. In this case, we can let the calculations run and test the value in the On-Exit. If the result is negative, we return 0 instead of the result. Of course, in this simplified example, we could have conditioned the initial return statement, but what if this calculation were extremely complex and could be calculated multiple ways, perhaps even in different subprocedures?

Final Thoughts

As you can see, while this addition to RPG may seem insignificant at first glance, it is extremely useful in practice. While there are certainly more uses for On-Exit than these few examples, I hope that they spur your creativity in finding uses for the feature. I find it to be a great addition to my arsenal! What are some ways you are using or will use On-Exit in your applications? I’d love to discuss it in the comments.

 

Brian May

Brian May, an IBM Power Systems Champion and Solutions Architect for Profound Logic Software, devotes the majority of his time to assisting customers with their modernization efforts. He frequently writes and speaks on topics related to RPG, JavaScript, and IBM i Modernization. Brian recently contributed his time and expertise to the new IBM i Modernization Redbook.

 

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: