1

I'm trying to understand the exception handling in PL/pgSQL but ...

Case 1:

CREATE OR REPLACE PROCEDURE ins ()
AS $$ DECLARE
i INT;
BEGIN
insert into scott.emp (empno) values (9000);
commit;
i:=1/0;
EXCEPTION WHEN OTHERS THEN
--rollback;
END $$ LANGUAGE plpgsql;

call ins();

I would guess the line is inserted, but it is not

CASE 2:

CREATE OR REPLACE PROCEDURE ins ()
AS $$ DECLARE
i INT;
BEGIN
insert into scott.emp (empno) values (9000);
commit;
--i:=1/0;
EXCEPTION WHEN OTHERS THEN
--rollback;
END $$ LANGUAGE plpgsql;

call ins();

Now, there is no div by zero , but alos no line in the table

Case 3:

CREATE OR REPLACE PROCEDURE ins ()
    AS $$ DECLARE
    i INT;
    BEGIN
    insert into scott.emp (empno) values (9000);
    commit;
    --i:=1/0;
    --EXCEPTION WHEN OTHERS THEN
    --rollback;
    END $$ LANGUAGE plpgsql;

    call ins();

Now the line is inserted. It seems that the Problen is my Exception Block, but why?

Thanks in advance. Marco

1

1 Answer 1

4

Silently throwing away your error message certainly does make debugging difficult.

CREATE OR REPLACE PROCEDURE ins ()
AS $$ DECLARE
i INT;
BEGIN
insert into scott.emp (empno) values (9000);
commit;
--i:=1/0;
EXCEPTION WHEN OTHERS THEN
raise notice E'%', SQLERRM;
END $$ LANGUAGE plpgsql;

Shows:

NOTICE:  cannot commit while a subtransaction is active

So this due to the documented limitation:

A transaction cannot be ended inside a block with exception handlers.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.