20
Sat, Apr
5 New Articles

Error Recovery in RPG Programs

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

One of the features I like most about CL is its ability to recover from errors using the Monitor Message (MONMSG) command. I've often thought that such a command would be a welcome addition to RPG.

Think about what happens when an RPG program finds an error. Suppose a program attempts to divide a number by a variable with a value of zero. At this point, if there are no error-handling measures in the program, the system stops executing the program and asks the operator what to do. This is not an elegant programming technique by any means. It would be preferable to be able to trap the error and take appropriate action.

In a CL program, you can use a global MONMSG command to trap these types of errors. This article shows you how you can use a combination of a subroutine and a data structure to do limited error recovery in RPG programs.

Two types of errors (or exceptions) may occur during program execution: program errors and file errors. To keep the discussion from getting unnecessarily long, this article only discusses program errors. Handling file errors is not very different.

The Program Status Data Structure

First, let me introduce you to the program status data structure (PSDS), a 429- byte area of memory that contains all sorts of useful information about a program. (Although the PSDS will be enhanced in ILE RPG, it is upwardly compatible from RPG/400.) To indicate that a data structure is to contain the program status information, code an S in position 18 of the input specification that defines the data structure. A program can have only one data structure defined as the PSDS, and that data structure must not be a multiple occurrence data structure. You may give the PSDS a name if you wish, but it's not required.

Subfields in the data structure are predefined (see 1). All subfields can be defined by their beginning and ending positions, but some of them may also be defined using a keyword name. If you use the keyword, left-align it in positions 44 through 51 of the input specification.

Subfields in the data structure are predefined (see Figure 1). All subfields can be defined by their beginning and ending positions, but some of them may also be defined using a keyword name. If you use the keyword, left-align it in positions 44 through 51 of the input specification.

The subfields in the PSDS come in handy for everyday programming. For example, if you print the name of a program in the page headers of a report, you don't have to hard-code the name. Instead, you can get the program name from positions 1 through 10 of the PSDS. This feature is helpful, since it eliminates the possibility that you might copy or rename the program but forget to change the program name in the page headers.

Instead of using the TIME opcode, you can get the system date and time from positions 276 through 281 and 282 through 287. Do you want to know who's running the program? The user profile name is in positions 254 through 263. The *PARMS subfield (positions 37 through 39) tells you how many parameters were passed into the program. This information lets you write programs that use a varying number of parameters.

All of this general information is interesting, but it's off the subject of error handling. The system updates certain subfields when errors occur. The information in these subfields tells you what caused the error, so you can take appropriate steps to recover.

The status subfield is continually updated as a program executes. A status code value greater than 99 indicates that an error occurred. For example, if your program attempts to divide by zero, the status code subfield will be updated with a value of 102. See the RPG/400 Reference manual for a list of status codes.

Exception type and number are other useful subfields. These subfields are the first three characters and the last four characters of the message ID. Your program can examine the contents of these subfields to determine how to continue.

Certain subfields are not useful for error recovery, but are useful to programmers investigating the problem after the fact. These subfields include: routine name, source member sequence number, exception data, last file used, status of the last file used, and cause of error RPG9001.

Defining the PSDS

You may write input specifications to define the subfields within each RPG program, but it's a good idea to define the program status data structure once and include that definition in all your programs. There are three advantages to this approach. You only write the code one time; the subfields have the same names in all your programs; and it's easier to write error routines that can be copied from one program to another.

You can define the PSDS in two ways: you can use the /COPY compiler directive, or you can define the data structure externally.

I prefer to use /COPY, so I'll discuss it first. Create a source member containing only the input specifications that define the data structure (see 2). In your application programs, code a /COPY statement at the point you would normally key the data structure. The format of the /COPY statement is:

I prefer to use /COPY, so I'll discuss it first. Create a source member containing only the input specifications that define the data structure (see Figure 2). In your application programs, code a /COPY statement at the point you would normally key the data structure. The format of the /COPY statement is:

/COPY library/source-file,member

The RPG compiler will retrieve the data structure specifications in the source member when it compiles your program.

Do not confuse this method with the /COPY auto report directive. You do not have to use the auto report function to use /COPY.

If you prefer to use an external definition, create a physical file with fields that correspond to the subfields of the program status data structure. (The file does not have to have a member.) In your RPG program, put an E in column 17 of the data structure definition, and the file name in positions 21 through 30. This will direct the compiler to use that file's definition to define the data structure.

Either method will save you work, since you define the program status data structure only once.

The Program Status Subroutine (*PSSR)

Once you've defined the PSDS, you need a way to execute an error routine when something unexpected happens in your program. RPG allows you to include a *PSSR subroutine, which is automatically executed when a program error occurs. The *PSSR subroutine can also be executed explicitly with the EXSR operation. The subroutine should include any calculations you want carried out in the event of a program error.

In factor 2 of the ENDSR instruction, you designate where to continue execution when the subroutine is completed. See 3 for a list of valid return-point values. The value may be a constant or a variable. Most of the examples in this article use a constant return point.

In factor 2 of the ENDSR instruction, you designate where to continue execution when the subroutine is completed. See Figure 3 for a list of valid return-point values. The value may be a constant or a variable. Most of the examples in this article use a constant return point.

You may notice that these values lend themselves to the RPG cycle. This fact makes it more difficult, though not impossible, to use *PSSR in programs that bypass the cycle.

Because there is no way to return to the next sequential instruction, when the *PSSR subroutine is automatically invoked, the usefulness of this technique is limited.

Building Error-Handling Routines

I have searched for a one-size-fits-all, error-handling routine, but I haven't found one yet because I don't always want to recover from an error in the same way.

A simple way to handle an unexpected error is to request a dump and cancel the program. 4 shows an RPG program that uses this approach. The canceled program will send escape message RPG9001 to the caller, so it can take appropriate action. The CL program in 5 alerts the system operator that the program has ended abnormally.

A simple way to handle an unexpected error is to request a dump and cancel the program. Figure 4 shows an RPG program that uses this approach. The canceled program will send escape message RPG9001 to the caller, so it can take appropriate action. The CL program in Figure 5 alerts the system operator that the program has ended abnormally.

Another approach is to have the program issue an error message and continue. The program in 6 writes an error line on the report it is producing and continues at the top of the detail calculations (*DETC). For your reference, partial DDS for the printer file is shown in 7. This method works in this small program, but it could be a problem if there were other calculations before the first READ. Another version, which uses the RPG cycle, is less subject to error (see 8). Note that the return point from *PSSR is *GETIN, which causes the program to read the next record from a primary or secondary file.

Another approach is to have the program issue an error message and continue. The program in Figure 6 writes an error line on the report it is producing and continues at the top of the detail calculations (*DETC). For your reference, partial DDS for the printer file is shown in Figure 7. This method works in this small program, but it could be a problem if there were other calculations before the first READ. Another version, which uses the RPG cycle, is less subject to error (see Figure 8). Note that the return point from *PSSR is *GETIN, which causes the program to read the next record from a primary or secondary file.

You can flag the error in other ways as well. In an interactive program you could, of course, notify the operator. You could also write a record to an error log file for later analysis.

Like all subroutines, the *PSSR subroutine may be executed by the EXSR operation. In 9, *PSSR is explicitly executed on a failed CALL to the program named in variable SUBPGM. When *PSSR finishes, the program will continue with the highlighted MOVEL instruction, since there is no value in factor 2 of the ENDSR line.

Like all subroutines, the *PSSR subroutine may be executed by the EXSR operation. In Figure 9, *PSSR is explicitly executed on a failed CALL to the program named in variable SUBPGM. When *PSSR finishes, the program will continue with the highlighted MOVEL instruction, since there is no value in factor 2 of the ENDSR line.

A general error-handling *PSSR is probably not possible, but you can settle on a few routines that will handle most of your needs. You can then choose the one that best fits each program.

Additional Considerations

There's an old saying that an ounce of prevention is worth a pound of cure. In no other area of RPG programming have I found this concept more applicable. Since it is difficult to recover from a program error, it is wise to take steps to avoid the automatic execution of *PSSR. For example, if there is even the remotest possibility that an array index may be out of bounds, test the array index with an IFxx operation, and do not permit code containing indexed references to the array to be executed. If the value of the variable in factor 2 of a DIV operation might be zero, test that variable for zero, and do not permit the division to take place if the test proves true. For an example of this test, see 10 .

There's an old saying that an ounce of prevention is worth a pound of cure. In no other area of RPG programming have I found this concept more applicable. Since it is difficult to recover from a program error, it is wise to take steps to avoid the automatic execution of *PSSR. For example, if there is even the remotest possibility that an array index may be out of bounds, test the array index with an IFxx operation, and do not permit code containing indexed references to the array to be executed. If the value of the variable in factor 2 of a DIV operation might be zero, test that variable for zero, and do not permit the division to take place if the test proves true. For an example of this test, see Figure 10 .

Another problem is that it is possible for *PSSR to call itself, which may result in an infinite loop. An infinite loop can occur when an instruction within *PSSRcauses a program error. A good solution is to check a status variable when entering the subroutine. If the variable indicates that *PSSR is active, exit the subroutine. Otherwise, set the status variable to a value to indicate the subroutine is active, and reset it to an inactive value at the end of the subroutine. This approach is covered in the RPG/400 Reference manual in the discussion of the File Exception/Error Subroutine. I've included an example in 11.

Another problem is that it is possible for *PSSR to call itself, which may result in an infinite loop. An infinite loop can occur when an instruction within *PSSRcauses a program error. A good solution is to check a status variable when entering the subroutine. If the variable indicates that *PSSR is active, exit the subroutine. Otherwise, set the status variable to a value to indicate the subroutine is active, and reset it to an inactive value at the end of the subroutine. This approach is covered in the RPG/400 Reference manual in the discussion of the File Exception/Error Subroutine. I've included an example in Figure 11.

Normal Termination

Now you have an idea of how you can take control of program errors. Earlier, I mentioned that there is another type of error: file errors. Working with file errors involves the same techniques presented here, but you need to use the INFDS and INFSR keywords on file continuation specifications. See the RPG/400 Reference manual for more details.

RPG's automatic recovery capabilities are not perfect, but they are usable, and it is worth your time to find out how to keep your programs from terminating abnormally.

Ted Holt is a programmer/analyst with Garan, Inc., in Starkville, Mississippi.

Reference

RPG Reference (SC09-1349, CD-ROM QBKA4E01).


Error Recovery in RPG Programs

Figure 1 Contents of PSDS

 UNABLE TO REPRODUCE GRAPHICS 
Error Recovery in RPG Programs

Figure 2 /COPY Member to Define Program Status Data Structu

 *. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 I* PROGRAM STATUS DATA STRUCTURE ISDS SDS I 1 10 S#PGM I 11 150S#STAT I 16 200S#PSTA I 21 28 S#SEQ# I 29 36 S#RTN I 37 39 S#PARM I 40 42 S#EXCT I 43 46 S#EXC# I 47 50 S#ODT# I 51 80 S#MWA I 81 90 S#LIB I 91 170 S#EXCD I 171 174 S#EXCI I 199 200 S#YEAR I 201 208 S#FILE I 209 243 S#FLST I 244 253 S#JOB I 254 263 S#USER I 264 2690S#JOB# I 270 2750S#EDAT I 276 2810S#SDAT I 282 2870S#STIM I 288 293 S#CDAT I 294 299 S#CTIM I 300 303 S#LEVL I 304 313 S#SRCF I 314 323 S#SRCL I 324 333 S#SRCM *. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 
Error Recovery in RPG Programs

Figure 3 Return Points for *PSSR

 *CANCL Cancel the program *DETC Detail calculations *DETL Detail output *GETIN Read next primary or secondary file record *OFL Overflow output routine *TOTC Total calculations *TOTL Total output blank Default error handler (if invoked automatically) Next sequential instruction (if invoked by EXSR) 
Error Recovery in RPG Programs

Figure 4 Using *PSSR to Cancel a Program

 *. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 H 1 FINFO IF E K DISK FOUTFO O E DISK C READ INFOREC 91 * C *IN91 DOWEQ'0' ... (detail calcs go here) C WRITEOUTFOREC C READ INFOREC 91 C ENDDO * C SETON LR * C *PSSR BEGSR C DUMP C ENDSR'*CANCL' *. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 
Error Recovery in RPG Programs

Figure 5 Monitoring for a Cancelled RPG Program

 PGM DCL &JOBNAME *CHAR 10 DCL &USER *CHAR 10 DCL &JOBNBR *CHAR 6 CALL SOME_PGM MONMSG RPG9001 EXEC(DO) RTVJOBA JOB(&JOBNAME) USER(&USER) NBR(&JOBNBR) SNDPGMMSG MSG('Program ended abnormally. See RPG dump + for job' *BCAT &JOBNBR *CAT '/' *CAT + &USER *TCAT '/' *CAT &JOBNAME) TOUSR(*SYSOPR) ENDDO ENDPGM 
Error Recovery in RPG Programs

Figure 6 Ignoring Invalid Records (Procedural Programming)

 *. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 FINFO IF E K DISK FPRTFILE O E 88 PRINTER I/COPY HOLT_T/PSSR,SDS C READ INFOREC 91 * C *IN91 DOWEQ'0' ... (detail calcs go here) C WRITEDTLLN C READ INFOREC 91 C ENDDO * C SETON LR * C *PSSR BEGSR C MOVELS#PGM A#PGM C MOVELS#STAT A#STAT C MOVELS#SEQ# A#SEQ# C WRITEABENDLN C ENDSR'*DETC ' *. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 
Error Recovery in RPG Programs

Figure 7 Portion of DDS for PRTFILE

 *. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 A R DTLLN SPACEA(1) ... (fields on detail line go here) A R ABENDLN SPACEA(1) A 1'UNEXPECTED ERROR; KEY:' A FLDA R + 1REFFLD(FLDA INFO) A + 1'PGM:' A A#PGM 10 + 1 A + 1'STATUS:' A A#STAT 5 + 1 A + 1'STMT:' A A#SEQ# 8 + 1 A + 1'RECORD IGNORED' *. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 
Error Recovery in RPG Programs

Figure 8 Ignoring Invalid Records (Cycle Programming)

 *. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 FINFO IP E K DISK FPRTFILE O E 88 PRINTER I/COPY HOLT_T/PSSR,SDS ... (detail calcs go here) C WRITEDTLLN * C *PSSR BEGSR C MOVELS#PGM A#PGM C MOVELS#STAT A#STAT C MOVELS#SEQ# A#SEQ# C WRITEABENDLN C ENDSR'*GETIN' *. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 
Error Recovery in RPG Programs

Figure 9 Explicit Execution of *PSSR

 *. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 C CALL SUBPGM 22 LO C *IN22 IFEQ *ON C EXSR *PSSR C ENDIF C MOVELFLDX FLDY ... (more calcs) C *PSSR BEGSR ... (error calcs go here) C ENDSR *. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 
Error Recovery in RPG Programs

Figure 10 Preventing the Possibility of Division by Zero

 *. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 C TOTAL IFNE *ZERO C SUM DIV TOTAL PCT1 C ELSE C MOVE *ZERO PCT1 C ENDIF *. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 
Error Recovery in RPG Programs

Figure 11 Preventing Recursive Execution of *PSSR

 *. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 C *PSSR BEGSR C MOVE '*CANCL' RTNPT 6 C PSRACT IFNE '1' C MOVE '1' PSRACT 1 C SELEC C S#STAT WHEQ 00100 C S#STAT OREQ 00121 C S#STAT OREQ 00122 C MOVE '*GETIN' RTNPT ... (more calcs) C S#STAT WHEQ 00211 C MOVE '*GETIN' RTNPT ... (more calcs) C OTHER ... (more calcs) C ENDSL C ENDIF C MOVE '0' PSRACT C ENDSRRTNPT *. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 
TED HOLT

Ted Holt is IT manager of Manufacturing Systems Development for Day-Brite Capri Omega, a manufacturer of lighting fixtures in Tupelo, Mississippi. He has worked in the information processing industry since 1981 and is the author or co-author of seven books. 


MC Press books written by Ted Holt available now on the MC Press Bookstore.

Complete CL: Fifth Edition Complete CL: Fifth Edition
Become a CL guru and fully leverage the abilities of your system.
List Price $79.95

Now On Sale

Complete CL: Sixth Edition Complete CL: Sixth Edition
Now fully updated! Get the master guide to Control Language programming.
List Price $79.95

Now On Sale

IBM i5/iSeries Primer IBM i5/iSeries Primer
Check out the ultimate resource and “must-have” guide for every professional working with the i5/iSeries.
List Price $99.95

Now On Sale

Qshell for iSeries Qshell for iSeries
Check out this Unix-style shell and utilities command interface for OS/400.
List Price $79.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

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: