MainframeMaster

COBOL Tutorial

COBOL AT Clause

The AT clause represents one of COBOL's most fundamental and versatile conditional processing mechanisms, serving as the cornerstone for exception handling, file processing control, and sophisticated program flow management. Far more than a simple conditional statement, the AT clause embodies COBOL's comprehensive approach to error handling and boundary condition management by providing precise control over program behavior when specific conditions are encountered, including end-of-file situations, invalid key conditions, overflow scenarios, and other exceptional circumstances that require specialized processing logic.

In enterprise computing environments, the AT clause serves as a critical component for robust application design, enabling developers to create resilient systems that handle unexpected conditions gracefully while maintaining data integrity and business continuity. Its capabilities extend far beyond simple error detection to encompass sophisticated exception handling strategies, recovery mechanisms, and conditional processing patterns that are essential for mission-critical applications operating in complex business environments where system reliability and data accuracy are paramount concerns.

Understanding AT Clause Architecture

The AT clause implements a sophisticated conditional processing and exception handling architecture that enables programs to respond intelligently to various boundary conditions and exceptional circumstances. This architecture encompasses multiple condition detection mechanisms, structured exception handling patterns, and recovery strategies that work together to provide robust, reliable program execution suitable for production business applications that must handle diverse operational scenarios and maintain consistent behavior under varying conditions.

At its core, the AT clause manages the complex interaction between normal program flow and exceptional conditions by providing structured mechanisms for detecting, handling, and recovering from various types of boundary situations. This includes sophisticated condition monitoring that automatically detects end-of-file conditions, invalid key situations, overflow scenarios, and other exceptional circumstances, as well as structured response mechanisms that enable programs to take appropriate action while maintaining data integrity and system stability.

The architectural design of the AT clause reflects COBOL's emphasis on reliability and maintainability. Unlike simple error checking mechanisms in other languages, the AT clause provides comprehensive exception handling capabilities that integrate seamlessly with COBOL's structured programming model, enabling developers to create robust applications that handle exceptional conditions gracefully while maintaining clear, readable code that is easy to understand and maintain over time.

Comprehensive AT Clause Capabilities:

  • End-of-File Processing: Sophisticated end-of-file detection and handling for sequential file processing with automatic cleanup and resource management.
  • Invalid Key Handling: Comprehensive invalid key condition management for indexed and relative file operations with detailed error reporting and recovery options.
  • Overflow Management: Advanced overflow condition detection and handling for arithmetic operations and data structure management with automatic scaling and recovery.
  • Exception Recovery: Structured exception recovery mechanisms that enable programs to continue processing after encountering exceptional conditions.
  • Conditional Branching: Intelligent conditional branching that directs program flow based on specific conditions and operational requirements.
  • Resource Cleanup: Automatic resource cleanup and management when exceptional conditions are encountered, ensuring system stability and data integrity.
  • Error Logging: Comprehensive error logging and reporting capabilities that provide detailed information about exceptional conditions for debugging and monitoring.
  • Business Logic Integration: Seamless integration with business logic that enables applications to handle exceptional conditions in ways that are appropriate for specific business requirements.

Enterprise Exception Handling Patterns

In enterprise environments, the AT clause enables sophisticated exception handling patterns that handle the complex requirements of business applications including transaction rollback scenarios, data validation failures, system resource constraints, and integration with enterprise monitoring and alerting systems. These patterns must balance system resilience with performance requirements while supporting the reliability and maintainability requirements of modern business systems.

Modern enterprise applications implement layered exception handling architectures where AT clauses work in conjunction with logging frameworks, monitoring systems, and business process management platforms. This layered approach enables applications to handle exceptional conditions at multiple levels while maintaining consistent error handling policies and providing comprehensive visibility into system behavior and operational characteristics.

The integration of AT clauses with contemporary application architectures enables sophisticated resilience patterns including circuit breaker implementations, retry mechanisms with exponential backoff, and graceful degradation strategies. These patterns support the availability and reliability requirements of modern business systems while leveraging COBOL's proven exception handling capabilities and structured programming features.

Performance and Reliability Considerations

The AT clause's performance characteristics are crucial for applications that must handle high transaction volumes, maintain responsive user interfaces, and provide consistent service levels even when encountering exceptional conditions. Performance optimization involves careful design of exception handling logic, efficient condition detection mechanisms, and strategic use of recovery procedures that minimize overhead while maximizing system reliability and user experience.

Advanced performance management includes predictive exception handling where potential problems are detected and addressed before they impact system operation, intelligent retry mechanisms that adapt to system conditions and failure patterns, and dynamic resource allocation that ensures adequate system resources are available for exception handling and recovery operations. These capabilities enable COBOL applications to maintain high performance even when dealing with complex exception scenarios.

Reliability planning for AT clause usage requires understanding both normal and exceptional operational patterns, failure mode analysis, and recovery time objectives. Modern implementations support comprehensive monitoring and alerting that provides real-time visibility into exception handling performance and enables proactive system management that prevents minor issues from becoming major operational problems.

AT Clause Syntax and Applications

Complete AT Clause Syntax Forms

The AT clause provides multiple syntax forms designed to handle different conditional processing scenarios and exception handling requirements. Understanding these variations and their appropriate applications is crucial for creating robust, maintainable programs that can handle the diverse operational conditions encountered in enterprise environments.

End-of-File Processing

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
READ file-name AT END PERFORM END-OF-FILE-PROCESSING NOT AT END PERFORM PROCESS-RECORD END-READ. *> Alternative syntax READ file-name AT END MOVE 'Y' TO EOF-FLAG DISPLAY 'End of file reached' END-READ.

End-of-file processing provides structured handling of file boundary conditions with automatic detection and appropriate response mechanisms.

Invalid Key Handling

cobol
1
2
3
4
5
6
7
8
9
10
11
12
READ indexed-file KEY IS record-key INVALID KEY PERFORM HANDLE-INVALID-KEY NOT INVALID KEY PERFORM PROCESS-VALID-RECORD END-READ. WRITE record-name INVALID KEY DISPLAY 'Duplicate key error: ' record-key PERFORM LOG-ERROR END-WRITE.

Invalid key handling manages key-related exceptions in indexed file operations with comprehensive error detection and recovery capabilities.

Overflow Conditions

cobol
1
2
3
4
5
6
7
8
9
10
11
12
ADD amount TO total-amount ON SIZE ERROR PERFORM HANDLE-OVERFLOW NOT ON SIZE ERROR PERFORM CONTINUE-PROCESSING END-ADD. COMPUTE result = value1 * value2 ON SIZE ERROR DISPLAY 'Arithmetic overflow detected' MOVE HIGH-VALUES TO result END-COMPUTE.

Overflow condition handling manages arithmetic and data size exceptions with automatic detection and appropriate response strategies.

Comprehensive AT Clause Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
IDENTIFICATION DIVISION. PROGRAM-ID. COMPREHENSIVE-AT-DEMO. *> Comprehensive demonstration of AT clause applications *> Covering exception handling, file processing, and control flow ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT INPUT-FILE ASSIGN TO "INPUT.DAT" ORGANIZATION IS SEQUENTIAL ACCESS MODE IS SEQUENTIAL FILE STATUS IS INPUT-FILE-STATUS. SELECT OUTPUT-FILE ASSIGN TO "OUTPUT.DAT" ORGANIZATION IS SEQUENTIAL ACCESS MODE IS SEQUENTIAL FILE STATUS IS OUTPUT-FILE-STATUS. SELECT MASTER-FILE ASSIGN TO "MASTER.DAT" ORGANIZATION IS INDEXED ACCESS MODE IS DYNAMIC RECORD KEY IS MASTER-KEY FILE STATUS IS MASTER-FILE-STATUS. SELECT ERROR-LOG ASSIGN TO "ERROR.LOG" ORGANIZATION IS SEQUENTIAL ACCESS MODE IS SEQUENTIAL FILE STATUS IS ERROR-FILE-STATUS. DATA DIVISION. FILE SECTION. FD INPUT-FILE RECORD CONTAINS 100 CHARACTERS. 01 INPUT-RECORD. 05 INPUT-ID PIC X(10). 05 INPUT-NAME PIC X(30). 05 INPUT-AMOUNT PIC 9(8)V99. 05 INPUT-TYPE PIC X(5). 05 FILLER PIC X(45). FD OUTPUT-FILE RECORD CONTAINS 120 CHARACTERS. 01 OUTPUT-RECORD. 05 OUTPUT-ID PIC X(10). 05 OUTPUT-NAME PIC X(30). 05 OUTPUT-PROCESSED-AMOUNT PIC 9(10)V99. 05 OUTPUT-STATUS PIC X(10). 05 OUTPUT-TIMESTAMP PIC X(14). 05 FILLER PIC X(44). FD MASTER-FILE RECORD CONTAINS 200 CHARACTERS. 01 MASTER-RECORD. 05 MASTER-KEY PIC X(10). 05 MASTER-NAME PIC X(50). 05 MASTER-BALANCE PIC S9(10)V99. 05 MASTER-STATUS PIC X(5). 05 MASTER-LAST-UPDATE PIC X(8). 05 FILLER PIC X(125). FD ERROR-LOG RECORD CONTAINS 150 CHARACTERS. 01 ERROR-RECORD. 05 ERROR-TIMESTAMP PIC X(14). 05 ERROR-TYPE PIC X(20). 05 ERROR-DESCRIPTION PIC X(100). 05 ERROR-RECORD-ID PIC X(10). 05 FILLER PIC X(6). WORKING-STORAGE SECTION. *> File status variables 01 FILE-STATUS-CODES. 05 INPUT-FILE-STATUS PIC X(2). 88 INPUT-FILE-OK VALUE "00". 88 INPUT-EOF VALUE "10". 88 INPUT-FILE-ERROR VALUE "30" THRU "99". 05 OUTPUT-FILE-STATUS PIC X(2). 88 OUTPUT-FILE-OK VALUE "00". 88 OUTPUT-FILE-ERROR VALUE "30" THRU "99". 05 MASTER-FILE-STATUS PIC X(2). 88 MASTER-FILE-OK VALUE "00". 88 MASTER-NOT-FOUND VALUE "23". 88 MASTER-DUPLICATE VALUE "22". 88 MASTER-FILE-ERROR VALUE "30" THRU "99". 05 ERROR-FILE-STATUS PIC X(2). 88 ERROR-FILE-OK VALUE "00". 88 ERROR-FILE-ERROR VALUE "30" THRU "99". *> Control flags and counters 01 PROCESSING-CONTROLS. 05 EOF-FLAG PIC X VALUE 'N'. 88 END-OF-FILE VALUE 'Y'. 88 NOT-END-OF-FILE VALUE 'N'. 05 ERROR-FLAG PIC X VALUE 'N'. 88 ERRORS-OCCURRED VALUE 'Y'. 88 NO-ERRORS VALUE 'N'. 05 RECORDS-READ PIC 9(8) VALUE ZERO. 05 RECORDS-PROCESSED PIC 9(8) VALUE ZERO. 05 RECORDS-WRITTEN PIC 9(8) VALUE ZERO. 05 ERRORS-ENCOUNTERED PIC 9(5) VALUE ZERO. 05 INVALID-KEYS PIC 9(5) VALUE ZERO. 05 OVERFLOW-CONDITIONS PIC 9(5) VALUE ZERO. *> Working variables for calculations 01 CALCULATION-VARIABLES. 05 WS-TOTAL-AMOUNT PIC S9(12)V99 VALUE ZERO. 05 WS-PROCESSED-AMOUNT PIC S9(12)V99. 05 WS-MULTIPLIER PIC 9(3)V99 VALUE 1.05. 05 WS-MAXIMUM-AMOUNT PIC 9(10)V99 VALUE 999999999.99. 05 WS-MINIMUM-AMOUNT PIC 9(8)V99 VALUE 0.01. *> Date and time variables 01 WS-CURRENT-DATETIME. 05 WS-CURRENT-DATE PIC X(8). 05 WS-CURRENT-TIME PIC X(6). 05 WS-TIMESTAMP PIC X(14). *> Error handling variables 01 ERROR-HANDLING-VARIABLES. 05 WS-ERROR-COUNT PIC 9(5) VALUE ZERO. 05 WS-ERROR-TYPE PIC X(20). 05 WS-ERROR-DESCRIPTION PIC X(100). 05 WS-RETRY-COUNT PIC 9(2) VALUE ZERO. 05 WS-MAX-RETRIES PIC 9(2) VALUE 3. PROCEDURE DIVISION. MAIN-PROCESSING. DISPLAY "=== Comprehensive AT Clause Demonstration ===". DISPLAY " ". PERFORM INITIALIZE-PROCESSING PERFORM OPEN-FILES PERFORM PROCESS-INPUT-FILE PERFORM DEMONSTRATE-INDEXED-FILE-OPERATIONS PERFORM DEMONSTRATE-ARITHMETIC-EXCEPTIONS PERFORM DEMONSTRATE-ADVANCED-EXCEPTION-HANDLING PERFORM CLOSE-FILES PERFORM DISPLAY-FINAL-STATISTICS DISPLAY " ". DISPLAY "AT clause demonstration completed successfully". STOP RUN. INITIALIZE-PROCESSING. DISPLAY "1. Initializing Exception Handling Processing:". DISPLAY " ==========================================". *> Get current date and time ACCEPT WS-CURRENT-DATE FROM DATE YYYYMMDD. ACCEPT WS-CURRENT-TIME FROM TIME. STRING WS-CURRENT-DATE WS-CURRENT-TIME DELIMITED BY SIZE INTO WS-TIMESTAMP. *> Initialize control variables SET NOT-END-OF-FILE TO TRUE. SET NO-ERRORS TO TRUE. MOVE ZERO TO RECORDS-READ RECORDS-PROCESSED RECORDS-WRITTEN ERRORS-ENCOUNTERED INVALID-KEYS OVERFLOW-CONDITIONS. DISPLAY " Processing initialized at: " WS-TIMESTAMP. DISPLAY " Error handling mechanisms activated". DISPLAY " ". OPEN-FILES. DISPLAY "2. Opening Files with Exception Handling:". DISPLAY " =======================================". *> Open input file with error handling OPEN INPUT INPUT-FILE. EVALUATE INPUT-FILE-STATUS WHEN "00" DISPLAY " Input file opened successfully" WHEN "35" DISPLAY " WARNING: Input file not found" PERFORM LOG-ERROR-CONDITION WHEN OTHER DISPLAY " ERROR opening input file: " INPUT-FILE-STATUS PERFORM LOG-ERROR-CONDITION PERFORM TERMINATE-PROCESSING END-EVALUATE. *> Open output file with error handling OPEN OUTPUT OUTPUT-FILE. IF NOT OUTPUT-FILE-OK DISPLAY " ERROR opening output file: " OUTPUT-FILE-STATUS PERFORM LOG-ERROR-CONDITION PERFORM TERMINATE-PROCESSING ELSE DISPLAY " Output file opened successfully" END-IF. *> Open master file with error handling OPEN I-O MASTER-FILE. EVALUATE MASTER-FILE-STATUS WHEN "00" DISPLAY " Master file opened successfully" WHEN "35" DISPLAY " Master file not found - creating new" OPEN OUTPUT MASTER-FILE CLOSE MASTER-FILE OPEN I-O MASTER-FILE WHEN OTHER DISPLAY " ERROR opening master file: " MASTER-FILE-STATUS PERFORM LOG-ERROR-CONDITION END-EVALUATE. *> Open error log file OPEN OUTPUT ERROR-LOG. IF ERROR-FILE-OK DISPLAY " Error log file opened successfully" ELSE DISPLAY " WARNING: Cannot open error log: " ERROR-FILE-STATUS END-IF. DISPLAY " ". PROCESS-INPUT-FILE. DISPLAY "3. Processing Input File with AT END Handling:". DISPLAY " ============================================". PERFORM READ-NEXT-RECORD. PERFORM UNTIL END-OF-FILE OR ERRORS-OCCURRED PERFORM PROCESS-SINGLE-RECORD PERFORM READ-NEXT-RECORD END-PERFORM. DISPLAY " Input file processing completed". DISPLAY " Records read: " RECORDS-READ. DISPLAY " Records processed: " RECORDS-PROCESSED. DISPLAY " ". READ-NEXT-RECORD. READ INPUT-FILE AT END SET END-OF-FILE TO TRUE DISPLAY " End of input file reached" NOT AT END ADD 1 TO RECORDS-READ IF RECORDS-READ = 1 DISPLAY " First record read successfully" END-IF END-READ. *> Check for read errors IF INPUT-FILE-ERROR DISPLAY " ERROR reading input file: " INPUT-FILE-STATUS PERFORM LOG-ERROR-CONDITION SET ERRORS-OCCURRED TO TRUE END-IF. PROCESS-SINGLE-RECORD. *> Validate input record IF INPUT-ID = SPACES OR INPUT-AMOUNT = ZERO DISPLAY " WARNING: Invalid record data for ID: " INPUT-ID PERFORM LOG-INVALID-RECORD EXIT PARAGRAPH END-IF. *> Process the record with exception handling PERFORM CALCULATE-PROCESSED-AMOUNT PERFORM UPDATE-MASTER-RECORD PERFORM WRITE-OUTPUT-RECORD ADD 1 TO RECORDS-PROCESSED. CALCULATE-PROCESSED-AMOUNT. *> Calculate processed amount with overflow handling COMPUTE WS-PROCESSED-AMOUNT = INPUT-AMOUNT * WS-MULTIPLIER ON SIZE ERROR DISPLAY " OVERFLOW: Amount too large for ID: " INPUT-ID MOVE WS-MAXIMUM-AMOUNT TO WS-PROCESSED-AMOUNT ADD 1 TO OVERFLOW-CONDITIONS PERFORM LOG-OVERFLOW-CONDITION NOT ON SIZE ERROR *> Check if result is within business limits IF WS-PROCESSED-AMOUNT > WS-MAXIMUM-AMOUNT DISPLAY " WARNING: Processed amount exceeds limit for ID: " INPUT-ID MOVE WS-MAXIMUM-AMOUNT TO WS-PROCESSED-AMOUNT END-IF END-COMPUTE. *> Add to total with overflow protection ADD WS-PROCESSED-AMOUNT TO WS-TOTAL-AMOUNT ON SIZE ERROR DISPLAY " OVERFLOW: Total amount overflow detected" SUBTRACT WS-PROCESSED-AMOUNT FROM WS-TOTAL-AMOUNT ADD 1 TO OVERFLOW-CONDITIONS PERFORM LOG-OVERFLOW-CONDITION END-ADD. UPDATE-MASTER-RECORD. *> Read master record with invalid key handling MOVE INPUT-ID TO MASTER-KEY. READ MASTER-FILE KEY IS MASTER-KEY INVALID KEY PERFORM CREATE-NEW-MASTER-RECORD NOT INVALID KEY PERFORM UPDATE-EXISTING-MASTER-RECORD END-READ. CREATE-NEW-MASTER-RECORD. DISPLAY " Creating new master record for ID: " INPUT-ID. MOVE INPUT-ID TO MASTER-KEY. MOVE INPUT-NAME TO MASTER-NAME. MOVE WS-PROCESSED-AMOUNT TO MASTER-BALANCE. MOVE "ACTIV" TO MASTER-STATUS. MOVE WS-CURRENT-DATE TO MASTER-LAST-UPDATE. WRITE MASTER-RECORD INVALID KEY DISPLAY " ERROR: Cannot create master record: " MASTER-KEY ADD 1 TO INVALID-KEYS PERFORM LOG-INVALID-KEY-CONDITION END-WRITE. UPDATE-EXISTING-MASTER-RECORD. DISPLAY " Updating existing master record for ID: " INPUT-ID. ADD WS-PROCESSED-AMOUNT TO MASTER-BALANCE ON SIZE ERROR DISPLAY " OVERFLOW: Master balance overflow for ID: " INPUT-ID SUBTRACT WS-PROCESSED-AMOUNT FROM MASTER-BALANCE ADD 1 TO OVERFLOW-CONDITIONS PERFORM LOG-OVERFLOW-CONDITION END-ADD. MOVE WS-CURRENT-DATE TO MASTER-LAST-UPDATE. REWRITE MASTER-RECORD INVALID KEY DISPLAY " ERROR: Cannot update master record: " MASTER-KEY ADD 1 TO INVALID-KEYS PERFORM LOG-INVALID-KEY-CONDITION END-REWRITE. WRITE-OUTPUT-RECORD. MOVE INPUT-ID TO OUTPUT-ID. MOVE INPUT-NAME TO OUTPUT-NAME. MOVE WS-PROCESSED-AMOUNT TO OUTPUT-PROCESSED-AMOUNT. MOVE "PROCESSED" TO OUTPUT-STATUS. MOVE WS-TIMESTAMP TO OUTPUT-TIMESTAMP. WRITE OUTPUT-RECORD. IF OUTPUT-FILE-OK ADD 1 TO RECORDS-WRITTEN ELSE DISPLAY " ERROR writing output record: " OUTPUT-FILE-STATUS PERFORM LOG-ERROR-CONDITION END-IF. DEMONSTRATE-INDEXED-FILE-OPERATIONS. DISPLAY "4. Indexed File Operations with Exception Handling:". DISPLAY " ================================================". PERFORM DEMONSTRATE-RANDOM-READ-OPERATIONS PERFORM DEMONSTRATE-SEQUENTIAL-READ-OPERATIONS PERFORM DEMONSTRATE-DELETE-OPERATIONS. DEMONSTRATE-RANDOM-READ-OPERATIONS. DISPLAY " Random Read Operations:". *> Attempt to read specific records MOVE "TEST000001" TO MASTER-KEY. READ MASTER-FILE KEY IS MASTER-KEY INVALID KEY DISPLAY " Record not found: " MASTER-KEY NOT INVALID KEY DISPLAY " Found record: " MASTER-KEY " Balance: $" MASTER-BALANCE END-READ. MOVE "NONEXIST01" TO MASTER-KEY. READ MASTER-FILE KEY IS MASTER-KEY INVALID KEY DISPLAY " Expected: Record not found: " MASTER-KEY NOT INVALID KEY DISPLAY " Unexpected: Found record: " MASTER-KEY END-READ. DEMONSTRATE-SEQUENTIAL-READ-OPERATIONS. DISPLAY " Sequential Read Operations:". *> Start sequential reading from beginning MOVE LOW-VALUES TO MASTER-KEY. START MASTER-FILE KEY IS GREATER THAN MASTER-KEY INVALID KEY DISPLAY " No records in master file" NOT INVALID KEY PERFORM READ-NEXT-MASTER-RECORD PERFORM 5 TIMES READ MASTER-FILE NEXT RECORD AT END DISPLAY " End of master file reached" EXIT PERFORM NOT AT END PERFORM READ-NEXT-MASTER-RECORD END-READ END-PERFORM END-START. READ-NEXT-MASTER-RECORD. DISPLAY " Master record: " MASTER-KEY " " MASTER-NAME(1:20). DEMONSTRATE-DELETE-OPERATIONS. DISPLAY " Delete Operations:". *> Attempt to delete a record MOVE "DELETE001" TO MASTER-KEY. READ MASTER-FILE KEY IS MASTER-KEY INVALID KEY DISPLAY " Cannot delete - record not found: " MASTER-KEY NOT INVALID KEY DELETE MASTER-FILE RECORD INVALID KEY DISPLAY " ERROR deleting record: " MASTER-KEY NOT INVALID KEY DISPLAY " Record deleted successfully: " MASTER-KEY END-DELETE END-READ. DEMONSTRATE-ARITHMETIC-EXCEPTIONS. DISPLAY "5. Arithmetic Exception Handling:". DISPLAY " ===============================". PERFORM DEMONSTRATE-OVERFLOW-CONDITIONS PERFORM DEMONSTRATE-DIVISION-BY-ZERO PERFORM DEMONSTRATE-SIZE-ERROR-HANDLING. DEMONSTRATE-OVERFLOW-CONDITIONS. DISPLAY " Overflow Condition Demonstrations:". *> Demonstrate addition overflow MOVE 999999999.99 TO WS-PROCESSED-AMOUNT. ADD 1000.00 TO WS-PROCESSED-AMOUNT ON SIZE ERROR DISPLAY " Addition overflow detected and handled" ADD 1 TO OVERFLOW-CONDITIONS NOT ON SIZE ERROR DISPLAY " Addition completed: " WS-PROCESSED-AMOUNT END-ADD. *> Demonstrate multiplication overflow MOVE 999999.99 TO WS-PROCESSED-AMOUNT. MULTIPLY 1000 BY WS-PROCESSED-AMOUNT ON SIZE ERROR DISPLAY " Multiplication overflow detected and handled" ADD 1 TO OVERFLOW-CONDITIONS NOT ON SIZE ERROR DISPLAY " Multiplication completed: " WS-PROCESSED-AMOUNT END-MULTIPLY. DEMONSTRATE-DIVISION-BY-ZERO. DISPLAY " Division by Zero Handling:". MOVE ZERO TO WS-MULTIPLIER. DIVIDE 1000 BY WS-MULTIPLIER GIVING WS-PROCESSED-AMOUNT ON SIZE ERROR DISPLAY " Division by zero detected and handled" MOVE 1.00 TO WS-MULTIPLIER MOVE ZERO TO WS-PROCESSED-AMOUNT NOT ON SIZE ERROR DISPLAY " Division completed: " WS-PROCESSED-AMOUNT END-DIVIDE. DEMONSTRATE-SIZE-ERROR-HANDLING. DISPLAY " Size Error Handling:". *> Demonstrate field size limitations MOVE 12345678901234567890 TO WS-PROCESSED-AMOUNT ON SIZE ERROR DISPLAY " Size error detected - value too large" MOVE 999999999.99 TO WS-PROCESSED-AMOUNT NOT ON SIZE ERROR DISPLAY " Value assigned successfully" END-MOVE. DEMONSTRATE-ADVANCED-EXCEPTION-HANDLING. DISPLAY "6. Advanced Exception Handling Patterns:". DISPLAY " ======================================". PERFORM DEMONSTRATE-RETRY-LOGIC PERFORM DEMONSTRATE-GRACEFUL-DEGRADATION PERFORM DEMONSTRATE-RESOURCE-CLEANUP. DEMONSTRATE-RETRY-LOGIC. DISPLAY " Retry Logic Implementation:". MOVE ZERO TO WS-RETRY-COUNT. PERFORM UNTIL WS-RETRY-COUNT >= WS-MAX-RETRIES ADD 1 TO WS-RETRY-COUNT *> Simulate an operation that might fail IF WS-RETRY-COUNT < 3 DISPLAY " Attempt " WS-RETRY-COUNT " failed - retrying" ELSE DISPLAY " Attempt " WS-RETRY-COUNT " succeeded" EXIT PERFORM END-IF END-PERFORM. IF WS-RETRY-COUNT >= WS-MAX-RETRIES DISPLAY " Maximum retries exceeded - operation failed" END-IF. DEMONSTRATE-GRACEFUL-DEGRADATION. DISPLAY " Graceful Degradation:". *> Simulate a service that might be unavailable DISPLAY " Primary service unavailable - using fallback" DISPLAY " Fallback processing completed successfully" DISPLAY " System continues with reduced functionality". DEMONSTRATE-RESOURCE-CLEANUP. DISPLAY " Resource Cleanup:". DISPLAY " Cleaning up temporary resources" DISPLAY " Releasing file locks" DISPLAY " Freeing memory allocations" DISPLAY " Resource cleanup completed". CLOSE-FILES. DISPLAY "7. Closing Files with Exception Handling:". DISPLAY " =======================================". CLOSE INPUT-FILE. IF NOT INPUT-FILE-OK DISPLAY " WARNING: Error closing input file: " INPUT-FILE-STATUS ELSE DISPLAY " Input file closed successfully" END-IF. CLOSE OUTPUT-FILE. IF NOT OUTPUT-FILE-OK DISPLAY " WARNING: Error closing output file: " OUTPUT-FILE-STATUS ELSE DISPLAY " Output file closed successfully" END-IF. CLOSE MASTER-FILE. IF NOT MASTER-FILE-OK DISPLAY " WARNING: Error closing master file: " MASTER-FILE-STATUS ELSE DISPLAY " Master file closed successfully" END-IF. CLOSE ERROR-LOG. IF NOT ERROR-FILE-OK DISPLAY " WARNING: Error closing error log: " ERROR-FILE-STATUS ELSE DISPLAY " Error log closed successfully" END-IF. DISPLAY " ". DISPLAY-FINAL-STATISTICS. DISPLAY "8. Final Processing Statistics:". DISPLAY " ============================". DISPLAY " Records read: " RECORDS-READ. DISPLAY " Records processed: " RECORDS-PROCESSED. DISPLAY " Records written: " RECORDS-WRITTEN. DISPLAY " Total amount processed: $" WS-TOTAL-AMOUNT. DISPLAY " Errors encountered: " ERRORS-ENCOUNTERED. DISPLAY " Invalid key conditions: " INVALID-KEYS. DISPLAY " Overflow conditions: " OVERFLOW-CONDITIONS. IF ERRORS-ENCOUNTERED > 0 OR INVALID-KEYS > 0 OR OVERFLOW-CONDITIONS > 0 DISPLAY " ** ATTENTION: Exception conditions were encountered **" DISPLAY " Review error log for detailed information" ELSE DISPLAY " All processing completed without exceptions" END-IF. LOG-ERROR-CONDITION. ADD 1 TO ERRORS-ENCOUNTERED. SET ERRORS-OCCURRED TO TRUE. MOVE WS-TIMESTAMP TO ERROR-TIMESTAMP. MOVE "FILE ERROR" TO ERROR-TYPE. MOVE "File operation error encountered" TO ERROR-DESCRIPTION. MOVE SPACES TO ERROR-RECORD-ID. IF ERROR-FILE-OK WRITE ERROR-RECORD END-IF. LOG-INVALID-RECORD. ADD 1 TO ERRORS-ENCOUNTERED. MOVE WS-TIMESTAMP TO ERROR-TIMESTAMP. MOVE "DATA ERROR" TO ERROR-TYPE. MOVE "Invalid record data detected" TO ERROR-DESCRIPTION. MOVE INPUT-ID TO ERROR-RECORD-ID. IF ERROR-FILE-OK WRITE ERROR-RECORD END-IF. LOG-INVALID-KEY-CONDITION. MOVE WS-TIMESTAMP TO ERROR-TIMESTAMP. MOVE "INVALID KEY" TO ERROR-TYPE. MOVE "Invalid key condition encountered" TO ERROR-DESCRIPTION. MOVE MASTER-KEY TO ERROR-RECORD-ID. IF ERROR-FILE-OK WRITE ERROR-RECORD END-IF. LOG-OVERFLOW-CONDITION. MOVE WS-TIMESTAMP TO ERROR-TIMESTAMP. MOVE "OVERFLOW" TO ERROR-TYPE. MOVE "Arithmetic overflow condition detected" TO ERROR-DESCRIPTION. MOVE INPUT-ID TO ERROR-RECORD-ID. IF ERROR-FILE-OK WRITE ERROR-RECORD END-IF. TERMINATE-PROCESSING. DISPLAY " CRITICAL ERROR: Terminating processing". PERFORM CLOSE-FILES. STOP RUN.

Best Practices and Guidelines

Recommended Practices

  • Always handle AT END conditions in file processing
  • Use INVALID KEY handling for indexed file operations
  • Implement ON SIZE ERROR for arithmetic operations
  • Provide meaningful error messages and logging
  • Design graceful degradation strategies
  • Implement retry logic for transient failures
  • Test exception handling paths thoroughly
  • Document exception handling strategies

Common Pitfalls

  • Not handling end-of-file conditions properly
  • Ignoring invalid key conditions in file operations
  • Not checking for arithmetic overflow conditions
  • Poor error message design and logging
  • Not implementing proper cleanup procedures
  • Inadequate testing of exception scenarios
  • Not considering recovery strategies
  • Overcomplicating exception handling logic

Related COBOL Concepts

  • READ - File input operations with exception handling
  • WRITE - File output operations with error detection
  • INVALID KEY - Key-related exception handling
  • ON SIZE ERROR - Arithmetic exception management
  • FILE STATUS - Comprehensive error code handling
  • END-READ/END-WRITE - Structured exception handling
  • NOT AT END - Positive condition handling
  • EXCEPTION - General exception handling mechanisms