tags:

views:

492

answers:

3

How do I get a PL/SQL program to end halfway through? I haven't been able to find any way to gracefully end the program if an exception occurs - if I handle it, it loops back into the code.

Basically what I want to do is force the app not to run in certain conditions. So, I want to add something like this to the top of the program:

BEGIN
    IF [condition]
        EXIT
    END IF
    [the rest of the program]
END

The suggested way is to throw an exception, but the block may well be an inner block - so the program outside of the block just keeps going.

+1  A: 

I don't know PL/SQL but why don't you try (using your words):

BEGIN
    IF [!condition]
        [the rest of the program]
    END IF
END

Just thinking

victor hugo
+5  A: 

You can use RETURN

MWATSON@> set serveroutput on
MWATSON@> !cat test.sql

BEGIN
 IF 1 = 1 THEN
    DBMS_OUTPUT.PUT_LINE('ABOUT TO EXIT');
    RETURN;
  END IF;
  DBMS_OUTPUT.PUT_LINE('DID NOT EXIT');
END;

MWATSON@> @test
  8  /
ABOUT TO EXIT

PL/SQL procedure successfully completed.

MWATSON@>
Matthew Watson
+1  A: 

If you raise an exception that the block does not handle, the exception is always raised to the caller. So the easiest way to stop processing is raise an exception that is not handled anywhere in the call stack.

e.g.

DECLARE
    e_halt_processing EXCEPTION;
BEGIN
    IF [condition] THEN
        RAISE e_halt_processing;
    END IF;
    [the rest of the program]
END;
Jeffrey Kemp
In other words, it doesn't matter if this is in an inner block - as long as the outer block does not handle the exception, it will not "loop back" into the inner block but will be propogated to its caller.
Jeffrey Kemp
exceptions shouldn't be used to jump over code. you're reinventing goto.
antony.trupe
I disagree.PL/SQL doesn't support the "goto" statement; and raising an exception is quite different thing to "jumping over code".If the current block hits a condition that it is not designed to cope with, raising an exception is the way you can advise the calling process of that condition.
Jeffrey Kemp