ILERPG.com β€” IBM i Β· ILE RPG Β· AS400 Mastery
2 min readΒ· Admin

MONITOR and ON-ERROR: Handling Errors in ILE RPG on Purpose

A program that ends with an unhandled error stops at the failing statement and waits for an operator to answer an inquiry message. In a batch run, that can hold up everything scheduled after it. Structured error handling lets a program decide in advance what each kind of failure should mean.

MONITOR groups

MONITOR marks a block of statements. If one of them raises an error, control passes to the first ON-ERROR clause that matches the status code, and execution continues after ENDMON. A clause can list several codes, or use *PROGRAM, *FILE, or *ALL.

monitor;
  avgCost = totalCost / unitCount;
on-error STS_DIVIDE_BY_ZERO;
  avgCost = 0;
on-error *all;
  errorCount += 1;
endmon;

Status codes worth knowing

00102 divide by zero, 00112 invalid date, 00121 array index out of range, 00202 called program or procedure failed, 00907 decimal data error, 01021 duplicate key, 01218 record lock. Defining them as named constants keeps every ON-ERROR readable.

The (E) extender

Coding (E) on an operation β€” CHAIN(E), WRITE(E) β€” suppresses the exception and sets %ERROR, with %STATUS holding the code. That is the better fit when a program must react to the outcome of one specific operation, such as telling a record lock apart from a missing record.

Calls, clean-up, and diagnostics

An error a subprocedure does not handle ends that call; in the caller, the call statement fails with 00202. ON-EXIT gives a subprocedure a section that always runs as it ends, normally or not. The program status data structure captures the message ID, procedure name, and job for a useful log entry.

SQL is different

Embedded SQL does not raise RPG exceptions. A failed UPDATE sets SQLSTATE and carries on, so every SQL statement needs its own check β€” a point Lesson 28 builds on.

Get the lesson

Lesson 26, β€œError Handling Foundations: MONITOR/ON-ERROR,” is part of Beginner ILE RPG in IBM i ILE RPG Mastery and is available at ILERPG.com for USD 10. The complete Beginner ILE RPG series β€” all 18 lessons β€” is USD 180, or USD 135 with coupon code RPG30, which takes 25% off when you purchase the full series.