0

I have a anonymous block like below

DECLARE
exc1 EXCEPTION;
i integer:='1';
BEGIN
 BEGIN
    IF i = 1 THEN
        RAISE exc1;
    END IF;

 EXCEPTION
    WHEN OTHERS THEN
        raise_application_error(-20481,
                    'Error while inserting/update into Table- ' ||
                    SQLERRM);
 END;
EXCEPTION
WHEN exc1 THEN
    raise_application_error(-20001, 'test123');

END;

I just want to raise the exc1 exception. But here instead when others then exception is raising. I specifically raise the exception exc1 in if condition block so it has to call right?

1
  • The reason your OTHERS exception handler is being executed is because the exc1 handler is not in scope. when your if block executes its true code. Commented Aug 12, 2020 at 1:46

1 Answer 1

1

The best option here is to have just one exception block:

DECLARE
exc1 EXCEPTION;
i integer:='1';
BEGIN
    IF i = 1 THEN
        RAISE exc1;
    END IF;
EXCEPTION
    WHEN exc1 THEN
        raise_application_error(-20001, 'test123');

    WHEN OTHERS THEN
        raise_application_error(-20481,
                    'Error while inserting/update into Table- ' ||
                    SQLERRM);
END;
/

But if you really need nested anonymous block with own exceptions blocks, you need to add one more exception handler:

DECLARE
exc1 EXCEPTION;
i integer:='1';
BEGIN
     BEGIN
        IF i = 1 THEN
            RAISE exc1;
        END IF;

     EXCEPTION
        WHEN exc1 THEN
            raise;
        WHEN OTHERS THEN
            raise_application_error(-20481,
                        'Error while inserting/update into Table- ' ||
                        SQLERRM);
     END;
EXCEPTION
    WHEN exc1 THEN
        raise_application_error(-20001, 'test123');
END;
/

PS. I'd suggest you do not use when others then without adding original exception into the error stack, ie 3rd parameter of raise_application_error() should be true:

DECLARE
exc1 EXCEPTION;
i integer:='1';
BEGIN
    IF i = 1 THEN
        RAISE exc1;
    END IF;
EXCEPTION
    WHEN exc1 THEN
        raise_application_error(-20001, 'test123', true);

    WHEN OTHERS THEN
        raise_application_error(-20481,
                    'Error while inserting/update into Table- ' ||
                    SQLERRM
                    , true);
END;
/
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.