20
Sat, Apr
5 New Articles

Implementing ILE Condition Handlers

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

Condition handling is the ILE extension to exception handling, and it provides a wonderfully robust and flexible way to deal with errors; however, the when, why, and how of implementing conditions goes much deeper than it would first appear. So, in order to present conditions in a complete, logical framework, I will attempt in this article to address in general terms the broader topic of error handling—then deal with the specifics of condition handling.

Error Handling

Error handling is typically the last piece of each software development effort, even though it’s usually the first thing the user sees. Let’s face it; if there’s something that can go wrong in your code, your users are going to find it. And that’s what error handling is about. In the broadest of terms, there are three categories of errors: recoverable, unrecoverable, and unexpected.

Recoverable errors are those that—through either manual or programmatic intervention—can be handled without ending the program. An example of a manual intervention might be a record lock error for a batch update program. End the program that has the lock, and retry the operation. An example of a programmatic intervention might be a divide by zero in a report. Return a default value (usually zero) and continue with the report. In a case such as this, the program can continue on, and the user is happy.

Unrecoverable errors are more severe, and I’m not proud to say that my usual way of handling these errors is to let them pop up an exception message. I think we’ve all done it before; the thought process goes something like, “If it’s that broken, the user is going to have to notify someone anyway.” And, in the rough-and-tumble world of software deadlines, it seems like the 80/20 rule always applies to unrecoverable errors—it’s just not worth the effort.

Unexpected errors are even more difficult to handle. It’s one thing to program around errors you might expect to happen, such as a missing data queue or a locked object—but how do you handle an error you never even thought about? For example, how in the world do you code for an event such as a damaged system object? Do you put a MONMSG around every statement? Or, would you use a global MONMSG? Stick a *PSSR in every program? These are difficult questions, but they need to be answered.


You may have noticed that the last two error types are fatal errors: That is, the user will probably not be able to complete the task. Chances are, there are some serious system configuration problems, or something earlier in the job stream bombed out pretty spectacularly. In these cases, the primary purpose of an error handler is to provide information to the IS staff so that its members can diagnose and correct the problem, while attempting to do as little additional damage as possible. Nonfatal errors, on the other hand, are problems that can be addressed at the time, allowing the user to continue with the job at hand.

When Is a Resume Not a Retry?

Nonfatal errors have no good generic fix today. This is because there is no generic capability to retry a failing operation. When I first began my research into condition handling, I thought it might just provide that silver bullet. Unfortunately, it does not. As I’ll show a little later, IBM’s decision to implement a resume rather than a retry means that you can’t write a generic self-repair routine. Instead, to handle recoverable errors, you’ll have to do what you always did, which is check for errors wherever they might be expected to occur, and handle them with program-specific code. Too bad...one little architectural enhancement could have made all the difference in the world.

Handling Fatal Errors with Exceptions

This article is geared toward the new ILE error handling, so I won’t spend a lot of time on the subject of generalized error handling—certainly not the amount of time it deserves. However, after seeing some extraordinary sessions on message handling by Greg Veal at the Baltimore COMMON conference in October, I’m convinced that you could indeed implement a generalized error handler for both unrecoverable and unexpected errors using the existing exception message handling of the OPM.

Greg, who is the author of CL Programming for the IBM AS/400—Second Edition, presented the concept of monitoring for a single message, CPF9999, which is the general system function check message returned to all OPM programs. While Greg’s approach for standardized error handling is too involved for this article, in my opinion, it provides an excellent framework for handling all unrecoverable and unexpected errors in an OPM environment. By extending this concept to handle error message CEE9901, I believe it can provide the same capabilities for the ILE environment as well. If you want to learn more about this topic, I highly recommend that you try to attend his sessions at the next COMMON conference.

So, what am I saying? I’m saying that the vast majority of fatal error handling doesn’t require anything more sophisticated than a standardized error approach using the existing exception message capabilities that we’ve known and loved for so long. So then what’s the big deal about condition handlers? That’s what the rest of this article will focus on.

Conditions: The ILE Approach

ILE provides a new type of error handling capability. In fact, ILE provides two different new techniques: direct monitors and condition handlers. However, direct monitors are not implemented in RPG, and only to a very limited degree in COBOL (with clauses such as ON SIZE ERROR). Since I’m talking about application errors, then, direct monitor handlers are really not an issue. C programmers may want to learn more about direct monitoring capabilities. For the purposes of this article, I’ll focus on condition handlers.

A condition handler, as its name might imply, occurs in response to a condition. In ILE terms, condition is shorthand for exception condition. A condition is signaled when some sort of exception occurs. More specifically, a condition is usually signaled when a program stack entry generates a message of type *EXCEPTION (although they can also be generated for *STATUS and *NOTIFY messages).


Conditions are meant to be language- and even platform-independent. Unlike a *PSSR routine, which is specific to RPG, a condition handler can be written in RPG, COBOL or even C. Not only that, an RPG program can use a C condition handler, if the situation warrants it.

Conditions are also a little different than messages, in that when a condition is signaled, the program does not automatically end. Instead, there is something called a “resume cursor” which is intended to allow the program to continue processing after the conditioned has been addressed, or handled. It was this feature that first intrigued me about conditions, but that ultimately disappointed me.

Condition Handlers

The basic idea of a condition handler is going to be very familiar to someone with a strong background in C programming, especially API programming. It’s not going to be nearly so clear to those of us who came up with primarily a procedural HLL background in RPG or COBOL. That’s because condition handlers are implemented through a concept known in general programming circles as a callback routine.

Perhaps a better term in the context of an ILE article is callback procedure. A callback procedure is a procedure that is called asynchronously in response to an event. As a programmer, you don’t directly call the procedure—instead, you register it with the operating system to handle a specific event. If that event occurs, the operating system calls your procedure, passing it relevant information about exactly why the procedure is being called.

Examples at a slightly higher level are trigger programs and exit programs. Trigger programs are registered for and called in response to specific database events. Exit programs are called for even more general events, such as changes to user profiles or FTP events.

Registering a Condition Handler

How does one go about creating a condition handler? Well, the process is known as registering, and is performed by calling the CEEHDLR API. The program in Figure 1 shows how to call CEEHDLR. In short, you pass the address of the procedure to the API, and the procedure is called whenever a condition is signaled.

Remember, a handler is a runtime device and must be registered every time the job is run. This is different than, say, a default action for a message or a trigger for a physical file.

You can register multiple handlers, and there are some fairly straightforward rules about which handler is called first. Basically, they are executed in LIFO order, starting with handlers registered in the current call stack entry and then proceeding on up the stack. What this means is that you can specify a general condition handler at the very top entry in your activation group, and override it with more specific handlers farther down in your application.

To “unregister” a handler, you can call the CEEHDLU API. Alternatively, you can simply exit the call stack entry; this will automatically unregister any handlers registered by that entry.

Percolation, Promotion, and Resumption

There are three basic things a condition handler can do: percolate, promote, or resume. Here’s where the ILE environment is a little different than the OPM architecture. When programs call each other inside of an activation group in ILE, the line of ownership is a little more blurred. If I call a bound procedure that fails, I don’t necessarily want it to cancel my program. Think of a condition as an exception waiting to happen. It doesn’t cause a halt right away; a condition is just passed up the chain—that is, until it hits an activation group


boundary. At that point, the carriage turns into a pumpkin, so to speak, and the condition becomes an exception.

Percolation basically means to hand the condition off to the previous call stack entry. This is the default action. If the condition is percolated all the way up to an activation group boundary, it blossoms into a full-blown exception message, and standard message processing takes over. If you do not assign any condition handler, conditions will automatically get percolated.

Promotion means to change the condition. Rather than be limited to the system’s condition hierarchy, you may decide to build your own. Then, when you recognize a system-generated condition, you can transform it to one of your own conditions. This would allow you to group system conditions in ways that make sense to your application. For example, any message that indicates an object not found might be promoted to a Bad Environment message. Rather than checking for individual system conditions, a higher- level condition handler might just check for a bad environment condition and then take the appropriate action (such as changing the library list).

The final option is to resume after a condition is handled. Unfortunately, the implementation chosen by IBM was to point the resume cursor to the first machine instruction after the one that caused the error. Because of this, a failing instruction cannot be retried. In fact, when dealing with an HLL such as RPG, it may very well be that the next machine instruction will be one that requires the previous instruction to have completed successfully. When I attempted to resume after a failed CALL op code in RPG, I invariably got a pointer error, which I’m guessing is probably because the CALL op code was expected to set some value.

Had IBM, rather than forcing us to resume at the next operation, instead given us the ability to retry the operation that failed, the resume option would have much greater possible utility. It may even have been possible to use it as a framework to generically handle recoverable errors (such as environment setup). Unfortunately, that’s not the case. So, what good are conditions, then?

Using Condition Handlers: The Three O’Clock Blues

I’m sitting here listening to B.B. King and Eric Clapton performing the “Three O’Clock Blues” and thinking about one of those most dastardly of programming problems: the intermittent error. These are the ones that invariably only show up at 3 a.m. on the second Tuesday of the month during period close processing. While an exception message framework such as the one I outlined earlier is very effective for immediately identifying that an error has occurred and allowing the user to go on to something else, it has a serious deficiency when it comes to diagnostics. Specifically, by the time the exception message is handled up at the top level of the application, the called programs have all ended—so their states aren’t readily available for inspection. You can, of course, perform dumps all the way up the chain, but that’s a static view that may or may not provide the information you need.

A condition handler is a different animal. A condition handler is called as if it were a stack entry below the one that caused the error. That is, all the programs and procedures called up to the point of the error are still intact when the condition handler is called. And this got me to thinking.... What if my condition handler were to, say, call a command entry
screen? At this point, all of my programs, open files, overrides, and everything else about my environment are all intact. I can start debug and inspect program variables in their current state, check the data in work files, view the contents of QTEMP, and otherwise get a much more detailed look at the state of the application.

So, absent the ability to retry a failed operation, I decided to implement the next best thing: the generic error viewer.


The Generic Error Viewer

I decided to design a top level generic error viewer. This program would be the first program in my call stack and would in turn call my primary application. Since this wasn’t meant to be an application design session, my application turned out to be a program called MAINMENU, whose only purpose was to call a program that doesn’t exist (and thus cause an error).

Figure 2 shows the source for the RPG IV program MAINMENU. OK, so it’s not rocket science. In fact, it’s not even a good Hello World program. All it does is call the non-existent APP1PGM. When I run MAINMENU from the command line, I get the following:

Error occurred while calling program or procedure *LIBL/APP1PGM (C G D F).

Yeah, I’d guess an error would occur, since there is no such program. Now, I could write a generic exception-handling program that would call MAINMENU. In that case, the messages would be sent back upstream to my exception handler; however, as I noted before, by the time that program was informed of the problem, the state of the failing program would have been lost.

The Viewer Program

Instead, by using a condition handler, we can create a generic error-viewing program, ERRVIEW, and it’s not a lot of code. Figure 1 shows the entire program.

Registering a condition handler turns out to be quite simple and consists of two distinct pieces. First, define the handler routine via a prototype, then pass the address of the handler to the CEEHDLR API. This API takes three parameters:

• The address of the procedure
• The address of a token (which can be used to tell the handler what to do)
• The address of a feedback condition to identify errors

Unless you’ve created a very generic handler that can be registered to do different things in different circumstances, there’s little need for the token passed in the second parameter. (In my example, I just pass the address of a single character.) In more sophisticated implementations, you can use this token to communicate from the handler back to the program that registered it. You should, of course, check the condition to make sure your handler procedure was registered; in my example, I assume that it was.

So, the mainline for the generic error viewer consists of four steps: register handler, call application, unregister handler, and exit. The unregister step is not strictly needed in this case, since exiting the call stack entry that registered the handler will automatically unregister it, but I thought I’d show you how the unregister API (CEEHDLU) is called.

The Handler

The handler itself is even simpler. I threw in a little twist to show you how some of the fields work—I test for a specific condition—but even that wasn’t really necessary. However, let me tell you what the procedure does. When the program MAINMENU attempts to call APP1PGM, a condition is signaled. However, since I registered the procedure Handler way up in ERRVIEW, the system knows about it. So, rather than throw up that ugly exception message, OS/400 instead calls the procedure named Handler and passes it a condition identifying the error.

Handler takes the incoming condition and moves it into the generic condition structure named Feedback. I use this structure to segregate the various fields, although there is also an API (CEEDCOD) that will break apart a condition. Once I’ve broken apart the condition, I can then test for the specific condition. The associated message is broken


up into two fields, called facility code and message number in the documentation but called MsgPrefix and MsgNumber in my data structure. MsgPrefix contains the three-character prefix of the message ID, while MsgNumber contains the four-character message number, in hexadecimal. So, to look for MCH3401, I compare the prefix to MCH and the message number to X’3401’. If the condition matches what I am monitoring (in this case MCH3401), the handler calls QCMD, which would allow me to then begin some serious debugging of the program.

Compile the ERRVIEW program and call it. It will call MAINMENU, which will attempt to call APP1PGM. Now, instead of an error, you’ll see a command entry screen.

If you look at the program stack at this point, you’ll see something rather interesting, as shown in Figure 3. ERRVIEW is at the call to MAINMENU, MAINMENU is at the call to APP1PGM, and HANDLER is at the call to QCMD. As you can see, the state of the machine is perfectly preserved, and you can now debug the programs to see what went wrong.

For Further Consideration

This entire strategy is based on the fact that these programs are running in an ILE environment. The generic error viewer will only catch errors in the same activation group, so when you compile these programs, make sure to compile them in the QILE activation group (or in a named group). An interesting experiment would be to see what would happen if MAINMENU were in a different activation group. I’ll leave that one to you.

You’ve probably noticed that this version of ERRVIEW would only work in an interactive environment. In a batch program, I could instead call a program that sends a message to the system operator then goes into an indefinite wait on a message queue. Then, I could start a service job to perform much the same analysis as I would in an interactive environment. It’s very easy to code the handler program to test whether it’s running in a batch or interactive environment and proceed accordingly. Also, it wouldn’t be difficult to add a parameter that determines the program to call. So you see, with a few lines of code added, ERRVIEW could quickly become a pretty standard tool for just about any environment.

I’m still disappointed that resume doesn’t have a retry option. Without it, the resume strategy doesn’t have much use, especially in an RPG environment. However, while not as good as a generic error repair facility, a generic error monitor like ERRVIEW goes a long way toward trapping those annoying intermittent errors.


*===============================================================

* To compile:

*

* CRTBNDRPG PGM(XXX/ERRVIEW) SRCFILE(XXX/QRPGLESRC) +

* DFTACTGRP(*NO) ACTGRP(QILE)

*

*===============================================================

* Prototype for the condition handler.
D Handler PR
D Condition 12
D TokenIn *
D ResultCode 10I 0
D NewCondition 12

* Input parameters to the register handler API.
D HandlerProc S * PROCPTR INZ(%PADDR('HANDLER'))
D HandlerTokenA S * INZ(%ADDR(HandlerToken))
D HandlerToken S 1

* This data structure defines a condition. It can identify

* an error if the register API fails, and is also used during

* the call to the handler to identify the condition being signaled.
D Feedback DS
D Severity 5U 0
D MsgNumber 5U 0
D Flags 1
D MsgPrefix 3
D ISI 10U 0

* Message IDs are 4-digit hex values.
D Hex3401 S 5U 0 INZ(X'3401')

* Register the handler.
C callb(d) 'CEEHDLR'
C parm HandlerProc
C parm HandlerToken
C parm Feedback

* Start up the main menu.
C CALL 'MAINMENU'

* Unregister the handler. (Not necessary; exiting the program

* automatically unregisters it.)
C callb(d) 'CEEHDLU'
C parm HandlerProc
C parm Feedback

C MOVE *ON *INLR
C return

* Condition handling routine. Checks only for MCH3401

* (cannot resolve to object).
P Handler B
D Handler PI
D Condition 12
D TokenIn *
D ResultCode 10I 0
D NewCondition 12 *

C move Condition Feedback
C if (MsgPrefix = 'MCH')
C and (MsgNumber = Hex3401)
C call 'QCMD'
C endif
P E

Figure 1: Program ERRVIEW is a generic error viewer that illustrates how condition handlers work.

*===============================================================

* To compile:

*

* CRTBNDRPG PGM(XXX/MAINMENU) SRCFILE(XXX/QRPGLESRC) +

* DFTACTGRP(*NO) ACTGRP(QILE)

*

*===============================================================

C call 'APP1PGM'
C return

Figure 2: MAINMENU is a sad little program, because APP1PGM is not found.


Procedure Library Statement

EP_ERRVIEW PBDCON ERRVIEW PBDCON 43 P_MAINMENU PBDCON
MAINMENU PBDCON 1 lrRouterEh QSYS 549 HANDLER PBDCON 74

Figure 3: The program stack, at the time when the condition handler is invoked, shows that the machine state is preserved.


Joe Pluta

Joe Pluta is the founder and chief architect of Pluta Brothers Design, Inc. He has been extending the IBM midrange since the days of the IBM System/3. Joe uses WebSphere extensively, especially as the base for PSC/400, the only product that can move your legacy systems to the Web using simple green-screen commands. He has written several books, including Developing Web 2.0 Applications with EGL for IBM i, E-Deployment: The Fastest Path to the Web, Eclipse: Step by Step, and WDSC: Step by Step. Joe performs onsite mentoring and speaks at user groups around the country. You can reach him at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Joe Pluta available now on the MC Press Bookstore.

Developing Web 2.0 Applications with EGL for IBM i Developing Web 2.0 Applications with EGL for IBM i
Joe Pluta introduces you to EGL Rich UI and IBM’s Rational Developer for the IBM i platform.
List Price $39.95

Now On Sale

WDSC: Step by Step WDSC: Step by Step
Discover incredibly powerful WDSC with this easy-to-understand yet thorough introduction.
List Price $74.95

Now On Sale

Eclipse: Step by Step Eclipse: Step by Step
Quickly get up to speed and productivity using Eclipse.
List Price $59.00

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: