Question: What is the oncode built-in function used for?
Answer: The error handling in PL/1 is done by setting up processing for various conditions using the on statement. For example you can have on zerodivide to handle where the program attempts to divide by zero, on endfile (filename) to handle end of file processing on an input file, on fixedoverflow to handle when the numbers get too big for the fields in your program, etc. (Each of these can be abbreviated to on zdiv, on eof, and on fofl respectively). PL/1 has a number of these conditions that you can test for like this. Any conditions that you do not code or which do not have their own specific condition that can be tested for are handled by the generic on error processing.
That's where oncode comes in. It's not a great deal of use in some of the specific on conditions where you know what condition got you there but it's really useful in those blocks that can be called for several different reasons where it can be used to determine the exact reason for the call and it can also be used in the on error block to allow you to handle all of the conditions that you want to handle in your program but which don't have their own on condition.
As an example, if we have a VSAM file that we are reading and updating then we can test for errors on accessing the file using the on key condition. This allows us to handle errors on this file but it doesn't tell us if the error is that the key we are trying to access is not found, we are trying to add a duplicate key, the key might be invalid, or perhaps there's just not enough space in the file to add the new record. We can use the oncode built-in function within the on key block to work out which of these errors is the one that has occurred. Here's how:
ON KEY (MYFILE) BEGIN; IF ONCODE = 51 THEN PUT SKIP LIST('KEY NOT FOUND'); ELSE IF ONCODE = 52 THEN PUT SKIP LIST('DUPLICATE KEY'); ELSE IF ONCODE = 56 THEN PUT SKIP LIST('INVALID KEY'); ELSE IF ONCODE = 57 THEN PUT SKIP LIST('NOT ENOUGH DISK SPACE'); END;
There are hundreds of different oncodes that you can test for in the on error block in order to handle every imaginable error in your program. The complete list of on-codes can be found in the PL/1 Optimizing and Checkout Compilers: Language Reference Manual.
This article written by Stephen Chapman, Felgall Pty Ltd.