Friday, July 13, 2007

Using Monitor to trap errors

In good old RPG, what would we do if we wanted to check if the value in an alpha variable is integer or not?

Well, we would have defined a constant that has all integers or characters as the value (like '0123456789' for integers, I will not even try to demo the alpha equivalent) and then use the CheckR Opcode or the %CheckR BIF (built in function) to determine if the variable has any matches or not.

With the advent of Free RPG and the Monitor OpCode, there is a better way to do this. Here is how we can handle the error (using free form RPG) if the value in an alpha field is not integer:

Monitor;
CustInt = %Int(%Trim(Cust));
OsCust = %EditC(CustInt:'X'); // Customer number
On-Error; // If value is non-integer
OsCust = Cust;
EndMon;

The vlaue in the variable Cust should always be numeric, but sometimes, it turns out that it can be alpha too. When that happens, as the statement [CustInt = %Int(%Trim(Cust)); ] throwing an error condition is within the [Monitor - EndMon] block, the system flags an error condition and control skips to the statement following the "On-Error" statement. In my case, I just move the value in Cust as is to the OsCust field (which is also alpha)! The "On-Error" statement is executed only when an error condition exists within the Monitor block.

If the value is numeric, I make sure that it is padded with leading zeros (that is where the %EditC comes in handy) before moving it into the target alpha field.

No comments: