The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
CREATE OR REPLACE PACKAGE serial_package AUTHID DEFINERAS CURSOR emps_cur IS SELECT * FROM employees;END serial_package;/BEGIN OPEN serial_package.emps_cur;END;/BEGIN OPEN serial_package.emps_cur;END;/BEGIN OPEN serial_package.emps_cur;END;/ORA-06511: PL/SQL: cursor already openORA-06512: at "STEVEN.SERIAL_PACKAGE", line 5ORA-06512: at line 2
CREATE OR REPLACE PACKAGE serial_package AUTHID DEFINERAS CURSOR emps_cur IS SELECT * FROM employees;END serial_package;/CREATE OR REPLACE PROCEDURE use_packaged_cursor AUTHID DEFINERIS PROCEDURE cleanup IS BEGIN /* If called from exception section log the error */ IF SQLCODE <> 0 THEN /* Uses open source Logger utility: https://github.com/OraOpenSource/Logger */ logger.log_error ('use_packaged_cursor'); END IF; IF serial_package.emps_cur%ISOPEN THEN CLOSE serial_package.emps_cur; END IF; END cleanup;BEGIN OPEN serial_package.emps_cur; cleanup;EXCEPTION WHEN NO_DATA_FOUND THEN /* Clean up but do not re-raise (just to show that you might want different behaviors for different exceptions). */ cleanup; WHEN OTHERS THEN cleanup; RAISE;END;/BEGIN use_packaged_cursor;END;/PL/SQL procedure successfully completed.BEGIN use_packaged_cursor;END;/PL/SQL procedure successfully completed.