As in Java there is finally block which executed in all conditions.
Is there any similar function in Oracle PL/SQL which will be executed whenever procedure completes its execution even a return statement is used?
There is no equivalent of FINALLY but you can simulate it using nested PL/SQL blocks;
DECLARE
-- Your variables.
return_early BOOLEAN := FALSE;
BEGIN
-- Do something
DECLARE
-- Local variables in "try" block
BEGIN
-- Equivalent of "try" block
-- Do something that may raise an exception
IF some_condition THEN
return_early := TRUE;
-- you could also use "GOTO end_try;" rather than surrounding the
-- following statements in an "ELSE" statement
ELSE
-- Do something else that may raise an exception
END IF;
EXCEPTION
WHEN your_exception THEN
-- Equivalent of "catch" block
END;
<<end_try>>
-- Handle "finally" here, after end of nested block.
-- Note: you can only see variables declared in this outer block
-- not variables local to the nested PL/SQL block.
IF return_early THEN
RETURN;
END IF;
-- Continue and do more stuff.
END;
/
Another thread on Stackoverflow can help out here : Exception handling in pl/sql
Where Tony says :
"You can created nested blocks:"
create or replace procedure Trial
is
Begin
begin
---Block A--
EXCEPTION
when others then
insert into error_log values('error');
end;
begin
--Block B ----
end;
end;
The solutions provided in other answers does not implement exact try-catch-finally logic. E.g. the finally should be executed even if exception is reraised and even if in did not handled at all. In other words, the finally block must be called always.
The most similar behavior to Java's finally is the following. Unfortunately, here we have to wrap finally block into a procedure. We have no choice in PL/SQL.
declare
begin
declare
EXPECTED_EXCEPTION_RECOVERABLE exception;
EXPECTED_EXCEPTION_FATAL exception;
EXPECTED_EXCEPTION_UNHANDLED exception;
procedure finally is
begin
dbms_output.put_line('FINALLY section executed');
end;
begin
dbms_output.put_line('Trying dangerous section...');
/* uncomment to try different behavior */
--raise EXPECTED_EXCEPTION_RECOVERABLE;
--raise EXPECTED_EXCEPTION_FATAL;
--raise EXPECTED_EXCEPTION_UNHANDLED;
dbms_output.put_line('Dangerous section is executed successfully');
FINALLY();
exception
when EXPECTED_EXCEPTION_RECOVERABLE then
dbms_output.put_line('Recoverable exception handled.');
FINALLY();
when EXPECTED_EXCEPTION_FATAL then
dbms_output.put_line('Fatal exception handled and will be reraised');
FINALLY();
RAISE;
when OTHERS then
dbms_output.put_line('Unhandled exception is just reraised after finally section');
FINALLY();
RAISE;
end;
end;
/
It seems, this solution looks enough readable;
You can create a custom Exception and then Raise it at the end of your other exceptions, this custom exception must be on an outside block:
BEGIN
BEGIN
--DO SOME CODE HERE
EXCEPTION
WHEN NO_DATA_FOUND THEN
--HANDLE EXCEPTION
RAISE CUSTOM_EXCEPTION;
END;
EXCEPTION
WHEN CUSTOM_EXCEPTION THEN
--HANDLE THE FINALLY CODE HERE
END;
Related
I have 2 nested blocks in my program. If any error occurs in the 1st nested block then program will not execute further, and it will go to exception section and exit from the overall program.
But I do not want to be exit from my program. My program need to be executed for the 2nd nested block and further also, even an exception is raised in 1st nested block.
If I have program like this:
DECLARE
var_out VARCHAR2(10):= 'OUTER';
BEGIN
<<INNER1>>
DECLARE
var_in1 NUMBER:='INNER 1';
BEGIN
DBMS_OUTPUT.PUT_LINE(var_in1);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM);
END;
<<INNER2>>
DECLARE
var_in2 VARCHAR2(10):='INNER 2';
BEGIN
DBMS_OUTPUT.PUT_LINE(var_in2);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM);
END;
DBMS_OUTPUT.PUT_LINE(var_out);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM);
END;
in my program inner1 block will throw value error exception so the overall program will not be executed.
How do I execute inner2 and outer block, even exception raised in inner1 block?
Because your exception in INNER1 occurs within the declaration section, it is beyond the scope of the block's exception handler. You need to wrap the whole INNER1 block in another block with its own exception handler.
declare
var_out varchar2(10):= 'OUTER';
begin
<<INNER1>>
begin
declare
var_in1 number:='INNER 1';
begin
dbms_output.put_line(var_in1);
exception
when others then
dbms_output.put_line('Error in innermost INNER1');
end;
exception
when others then
dbms_output.put_line('Error in INNER1 wrapper');
end;
<<INNER2>>
declare
var_in2 varchar2(10):='INNER 2';
begin
dbms_output.put_line(var_in2);
exception
when others then
dbms_output.put_line('Error in INNER2');
end;
dbms_output.put_line(var_out);
exception
when others then
dbms_output.put_line('Error at top level');
end;
Output:
Error in INNER1 wrapper
INNER 2
OUTER
Probably both OTHERS handlers are not needed - the above is just to illustrate the structure.
I am trying to return list of number from a stored procedure. My stored procedure gets stopped in for loop when exception occur. I have added exception clause and control is going inside the exception clause to continue the loop but still no luck.
How to continue the loop when exception occur? Thanks.
CREATE OR REPLACE PROCEDURE getNumber(l_list IN CUSTOMLIST, l_output OUT NUMLIST)
IS
n_num varchar2(5);
BEGIN
l_output := NUMLIST();
FOR i IN l_list.FIRST .. l_list.LAST LOOP
l_output.EXTEND(l_list.LAST);
BEGIN
SELECT NUM into n_num
FROM sometable WHERE some condition;
l_output(i) := n_num;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('TRUE');
CONTINUE;
END;
END LOOP;
END;
Maybe you should handle other exceptions too.
Try with adding
WHEN OTHERS THEN
[statements]
The code I posted in question is working when I restart the SQL developer. Something was wrong at SQL developer level when I copy paste the EXCEPTION clause. But when I type the EXCEPTION clause it's started showing be no_data_found option and that one I selected and it worked.
I was playing around with Oracle exceptions and tried to do some preprocessing between EXCEPTION and the WHERE statements. That is,
EXCEPTION
some_operation_here();
WHEN yaddayadda THEN
...
PL/SQL Developer said that that wasn't kosher – oh well – but its error message intrigued me: it was expecting either WHEN or PRAGMA. I am not thoroughly familiar with all the PRAGMA directives, but it doesn't seem like any of them are applicable in an exception block unless for some reason you waited till this point to bind an error code to an exception you had declared earlier. Why would you ever need to use a PRAGMA directive here?
A little experimentation tells me that you can, in fact put a PRAGMA in the exception block, but I can't see much use to it. The following executes successfully, but the raised error triggers the OTHER section, not the section for the newly defined exception (e.g. it returns "Old exception"). It would appear that this is an undocumented feature.
DECLARE
v NUMBER;
new_divide_zero EXCEPTION;
BEGIN
v := 1 / 0;
EXCEPTION
PRAGMA EXCEPTION_INIT (new_divide_zero, -1476);
WHEN new_divide_zero THEN
DBMS_OUTPUT.put_line ('New exception');
WHEN OTHERS THEN
DBMS_OUTPUT.put_line ('Old exception');
END;
Similarly, I tried putting a AUTONOMOUS_TRANSACTION in the exception block, but it too appears to have no effect (in this case, both rows are inserted).
CREATE TABLE test_results (result VARCHAR2 (2000));
BEGIN
DECLARE
v NUMBER;
new_divide_zero EXCEPTION;
BEGIN
insert into test_results values ('Test Value');
v := 1 / 0;
EXCEPTION
PRAGMA AUTONOMOUS_TRANSACTION;
WHEN OTHERS THEN
INSERT INTO test_results
VALUES ('Old exception');
Commit;
END;
ROLLBACK;
END;
The Oracle documentation (12g, which is the version i tested this on) does not mention using PRAGMA in the exception block, so it's definitely undocumented. On the other hand, it doesn't seem to be much of a feature, as it doesn't appear to actually do anything...
WHEN { exception_name [ OR exception_name ]... | OTHERS } THEN
statement [ statement ]...
It is syntax error. To catch exception you must use following syntax:
declare
yaddayadda exception;
begin
...
exception
WHEN yaddayadda THEN
some_operation_here();
end;
You need to use pragma exception_Init to assign you custom exception with sql error code.
For example:
declre
l_id number;
e_resource_busy EXCEPTION;
PRAGMA EXCEPTION_INIT(e_resource_busy, -54);
begin
select id
into l_id
from job_table
where status = 'RUNNING'
for update nowait;
exception
WHEN e_resource_busy THEN
-- row is locked
some_operation_here();
end;
In pl/sql I have some inner begin, end blocks and "Exception Others" blocks.
When I throw my user defined exception from an inner block I just want to catch this exception in the last "Exception userdef" block, not in the inner "Exception Others" blocks.
Any idea?
It sounds like you have something like this:
BEGIN
BEGIN
BEGIN
DO_SOMETHING; -- raises USERDEF_EXCEPTION
EXCEPTION
WHEN OTHERS THEN
DIE_HORRIBLY;
END;
EXCEPTION
WHEN OTHERS THEN
DIE_EVEN_MORE_HORRIBLY;
END;
EXCEPTION
WHEN USERDEF_EXCEPTION THEN
DO_SOMETHING_REASONABLE;
WHEN OTHERS THEN
DIE_INCREDIBLY_HORRIBLY;
END;
and you want to DO_SOMETHING_REASONABLE rather than DIE_HORRIBLY or DIE_EVEN_MORE_HORRIBLY. Sorry - you can't do that without providing a handler in the inner blocks for your exception. You'll have to do something like:
BEGIN
BEGIN
BEGIN
DO_SOMETHING; -- raises USERDEF_EXCEPTION
EXCEPTION
WHEN USERDEF_EXCEPTION THEN
RAISE;
WHEN OTHERS THEN
DIE_HORRIBLY;
END;
EXCEPTION
WHEN USERDEF_EXCEPTION THEN
RAISE;
WHEN OTHERS THEN
DIE_EVEN_MORE_HORRIBLY;
END;
EXCEPTION
WHEN USERDEF_EXCEPTION THEN
DO_SOMETHING_REASONABLE;
WHEN OTHERS THEN
DIE_INCREDIBLY_HORRIBLY;
END;
Share and enjoy.
/* package */
CREATE OR REPLACE PACKAGE exceptions_pkg AS
user_defined_exception EXCEPTION;
END exceptions_pkg;
/* block */
DECLARE
l_var1 NUMBER;
BEGIN
DBMS_OUTPUT.PUT_LINE('one');
DECLARE
l_var2 NUMBER;
BEGIN
DBMS_OUTPUT.PUT_LINE('two');
IF 1 < 2 THEN
RAISE exceptions_pkg.user_defined_exception;
END IF;
DBMS_OUTPUT.PUT_LINE('three');
END;
DBMS_OUTPUT.PUT_LINE('four');
EXCEPTION
WHEN exceptions_pkg.user_defined_exception THEN
DBMS_OUTPUT.PUT_LINE('five');
END;
-- anonymous block completed
/*
one
two
five
*/
I have a few SQL (Select/Update/Insert) syntax that I will run inside PL/SQL one after another
is there any way to check if each syntax completed correctly and if there is some error it will not halt the whole PL/SQL, it will just return "OK" or "Not OK" to a variable so I can use it with IF?
UPDATE
I came up with this function, but it dose not seems to work, it returns 0 all time!
create or replace
FUNCTION EXECUTE_SQL(
V_SQL IN VARCHAR2 )
RETURN NUMBER
AS
V_RESULTS NUMBER := 1;
BEGIN
BEGIN
EXECUTE IMMEDIATE V_SQL;
EXCEPTION
WHEN OTHERS THEN
-- the following line is just for debugging!
dbms_output.put_line(SQLERRM);
V_RESULTS:= 0;
END;
RETURN V_RESULTS;
END EXECUTE_SQL;
what is wrong wit it (if any)!
cheers
if sql%rowcount > 0 then
-- insert or update statement affected sql%rowcount rows
end if;
As for the correct syntax: if the syntax is wrong, it won't even compile. If there's a data consistency error (such as divide by 0 error, or primary key violation) an exception will be thrown. Such exception can be caught in exception handlers
In the exception handler, you can then check sqlerrm for more details:
begin
update t set x = ...
exception when others then
dbms_output.put_line(SQLERRM);
end;
There are also a few predefined exceptions that you can check on:
begin
update t set x = ...
exception
when DUP_VAL_ON_INDEX
-- primary key or unique key violation
when OTHERS
-- other kind of exception
end;
If the syntax is not correct the entire block will be invalid, so you'll not be able to run it.
If you want to run all statements, despite that one can raise an exception, you can:
BEGIN
BEGIN
statement1;
EXCEPTION
when exception1 then
some commands or null;
when exception2 then
some commands or null;
END;
BEGIN
statement2;
EXCEPTION
when exception3 then
some commands or null;
when exception4 then
some commands or null;
END;
etc.
END;
Write show errors
begin
update t set x = ...
exception
when DUP_VAL_ON_INDEX
-- primary key or unique key violation
when OTHERS
-- other kind of exception
end;
/
show errors
It will show errors if any.