The ON EXCEPTION clause in COBOL provides error handling and recovery mechanisms. It allows programs to respond to errors and exceptions that occur during execution, enabling graceful error handling instead of program termination.
The ON EXCEPTION clause follows specific syntax patterns:
12345678* Basic ON EXCEPTION syntax statement ON EXCEPTION * Exception handling code PERFORM error-handling NOT ON EXCEPTION * Success handling code PERFORM success-processing END-EXCEPTION.
ON EXCEPTION handles errors, NOT ON EXCEPTION handles success.
123456789* File operation with exception handling OPEN INPUT data-file ON EXCEPTION DISPLAY "Error opening file: " data-file PERFORM file-error-handling NOT ON EXCEPTION DISPLAY "File opened successfully" PERFORM process-file END-EXCEPTION.
123456789* Method invocation with exception handling INVOKE object "method-name" USING parameter ON EXCEPTION DISPLAY "Method call failed" PERFORM method-error-handling NOT ON EXCEPTION DISPLAY "Method executed successfully" PERFORM continue-processing END-EXCEPTION.
Here are some practical uses of ON EXCEPTION in COBOL:
12345678910111213141516171819202122* Reading file with exception handling READ data-file ON EXCEPTION IF file-status = "10" DISPLAY "End of file reached" PERFORM end-of-file-processing ELSE DISPLAY "Read error: " file-status PERFORM read-error-handling END-IF NOT ON EXCEPTION PERFORM process-record END-EXCEPTION. * Writing file with exception handling WRITE output-record ON EXCEPTION DISPLAY "Write error: " file-status PERFORM write-error-handling NOT ON EXCEPTION ADD 1 TO records-written END-EXCEPTION.
Comprehensive file I/O error handling.
123456789101112131415161718192021* Database connection with exception handling INVOKE database "Connect" USING connection-string ON EXCEPTION DISPLAY "Database connection failed" PERFORM database-error-handling MOVE "N" TO connection-success NOT ON EXCEPTION DISPLAY "Database connected successfully" MOVE "Y" TO connection-success PERFORM database-operations END-EXCEPTION. * Data validation with exception handling INVOKE validator "ValidateData" USING input-data ON EXCEPTION DISPLAY "Data validation failed" PERFORM validation-error-handling NOT ON EXCEPTION DISPLAY "Data validation successful" PERFORM process-valid-data END-EXCEPTION.
Object method error handling for robust operations.
1. What is the primary purpose of the ON EXCEPTION clause in COBOL?
2. Where is ON EXCEPTION typically used?
3. What happens when an exception occurs and ON EXCEPTION is specified?
4. What is the relationship between ON EXCEPTION and NOT ON EXCEPTION?
5. Is ON EXCEPTION required for all operations?