PL/SQL Function and Exception - sql

I am new to PL/SQL and I am writing a somewhat complex script. In order to make the script a little cleaner, I would like to create many functions. However I am not very familiar with functions.
Can a function has VOID return type? If I have to have a return, how will it work with exception handling?
See below:
EX:
DECLARE
some_variable NUMBER;
FUNCTION myFunc1(pInput IN NUMBER) RETURN NUMBER
IS
BEGIN
-- DO SOMETHING
EXCEPTION
WHEN someException THEN
DBMS_OUTPUT.PUT_LINE('ERROR someException ');
WHEN Others THEN
DBMS_OUTPUT.PUT_LINE('ERROR');
-----------------------------
-- WHERE DO I PUT THE RETURN?
-----------------------------
END;
FUNCTION myFunc2(pInput IN NUMBER) -- CAN IT RETURN NOTH
IS
fun1Return NUMBER;
BEGIN
-- DO SOMETHING
fun1Return := myFunc1(1);
EXCEPTION
WHEN someException THEN
DBMS_OUTPUT.PUT_LINE('ERROR someException ');
WHEN Others THEN
DBMS_OUTPUT.PUT_LINE('ERROR');
END;
BEGIN
--- DO SOMETHING
some_variable := myFunc2(2);
EXCEPTION
WHEN someException THEN
DBMS_OUTPUT.PUT_LINE('ERROR someException ');
WHEN Others THEN
DBMS_OUTPUT.PUT_LINE('ERROR');
END;

This is covered pretty well in the documentation.
A function has to return before the exception handler, if you have one. But in your example you should not be catching the exceptions really as you are just squashing the errors, and you're assuming whoever calls this will be able to see the dbms_output which is not a safe assumption. If you don't re-raise the (or any) exception then you still need to return from the exception handlers as well as from the main body of the block:
FUNCTION myFunc1(pInput IN NUMBER) RETURN NUMBER
IS
BEGIN
-- DO SOMETHING
RETURN 0;
EXCEPTION
WHEN someException THEN
DBMS_OUTPUT.PUT_LINE('ERROR ' || SQLERRM);
-- how do you know where the exception was raised?
RETURN -1;
WHEN Others THEN
DBMS_OUTPUT.PUT_LINE('ERROR');
-- how does the caller know what went wrong?
RETURN -2;
END;
You're also hiding all details of the error and removing any hope of being able to find out what actually went wrong. Catching when others is particularly evil, especially if you don't re-raise the exception. If you really want to display your own message you should still re-raise the original exception, in which case you won't need to return again:
FUNCTION myFunc1(pInput IN NUMBER) RETURN NUMBER
IS
BEGIN
-- DO SOMETHING
RETURN 0;
EXCEPTION
WHEN someException THEN
DBMS_OUTPUT.PUT_LINE('ERROR ' || SQLERRM);
RAISE;
WHEN Others THEN
DBMS_OUTPUT.PUT_LINE('ERROR');
RAISE;
END;
Which is very slightly better but you still lose some information about the error stack. You probably don't really want to catch these at all:
FUNCTION myFunc1(pInput IN NUMBER) RETURN NUMBER
IS
BEGIN
-- DO SOMETHING
RETURN 0;
END;
The only reason to catch an exception really is if it's something you sort of expect and can handle elegantly. Anything else - especially other - is almost always better off left to propagate up the call stack.
You can also have multiple returns if you have branches in your function.
FUNCTION myFunc1(pInput IN NUMBER) RETURN NUMBER
IS
BEGIN
IF SOMETHING THEN
RETURN 1;
END IF;
RETURN 0;
END;
As #couling says, a function with no return is a procedure. Stripping the exception again:
PROCEDURE myProc2(pInput IN NUMBER)
IS
fun1Return NUMBER;
BEGIN
-- DO SOMETHING
fun1Return := myFunc1(1);
END;

Related

How to find what data caused Oracle function failure?

sorry if this not the right place.
I am doing a SQL SELECT statement, invoking a function. It's a large data dump - about 10,000 records.
I am calling a function to preform some calculations, but its failing.
One ore more of those records has bad data that is causing the function to crash.
Is there any way to see exactly what data caused the crash readily Or should I create some code to run the function by hand for each of 10,000 records? I could create code that generates the input data fairly straightforwardly, then run the function like this SELECT MY_FUNCT(1,1,1) FROM DUAL; but I am wondering if there is a better way.
For reference I am running the SQL query like this.
SELECT
MY_FUNCT(A.FOO, A.BAR)
FROM TABLE A
WHERE ....;
As others have said, you just need to handle the error and not raise it all the way. A neat way of doing this would be to create a wrapper function for your function that sometimes fails, you can declare this function within your select query using a with pl/sql clause:
Let's say this is your function that sometimes fails
create or replace function my_funct (inputnumber number)
return varchar2
is
sString varchar2(200);
begin
if inputnumber = 42 then
raise_application_error(-20001,'UH OH!');
end if;
sString := 'Input: '||inputnumber;
return sString;
end my_funct;
/
We can define a function that takes the same inputs, and just calls this function, then we just need to add some error handling (obviously never just rely on dbms_output to capture errors, this is just to make it obvious):
function my_funct_handle (inputnumber number)
return varchar2
is
begin
return my_funct (inputnumber => inputnumber);
exception when others then
dbms_output.put_line(sqlerrm||' at '||inputnumber);
return 'ERROR';
end;
And we can then just stick that in our query using with function
with
function my_funct_handler (inputnumber number)
return varchar2
is
begin
return my_funct (inputnumber => inputnumber);
exception when others then
dbms_output.put_line(sqlerrm||' at '||inputnumber);
return 'ERROR';
end;
select my_funct_handler (id), string_col
from as_table;
/
I get both the dbms_output text to describe the error and the ID but I could also filter on the results of that function to only show me the erroring rows:
with
function my_funct_handle (inputnumber number)
return varchar2
is
begin
return my_funct (inputnumber => inputnumber);
exception when others then
dbms_output.put_line(sqlerrm||' at '||inputnumber);
return 'ERROR';
end;
select my_funct_handle (id), string_col
from as_table
where my_funct_handle (id) = 'ERROR';
/
MY_FUNCT_HANDLE(ID)
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
STRI
----
ERROR
blah
ORA-20001: UH OH! at 42
ORA-20001: UH OH! at 42
(I get two errors shown in the dbms_output output as the function can be called multiple times - once as part of the select list and once as part of the where clause.)
One option is to handle the exception properly, e.g.
create or replace function my_funct(par_foo in number, par_bar in number)
return number
is
retval number;
begin
select sal
into retval
from emp
where ename = par_foo
and deptno = par_bar;
return par_foo/par_bar;
exception --> this
when no_data_found then
return null;
end;
If you want, you can even log those errors. How? Make the function autonomous transaction (so that it could write into the log table; you'll have to commit that insert). Store all relevant information (including SQLERRM). Once your code finishes, check what's written in the log file and then decide what to do.
Or, you could even continue current task by enclosing that select into its own begin-exception-end block within a loop, e.g.
begin
for cur_r in (select ... from ...) loop
begin
-- your current SELECT
SELECT
MY_FUNCT(A.FOO, A.BAR)
FROM TABLE A
WHERE ....;
exception
when others then
dbms_output.put_line(cur_r.some_value ||': '|| sqlerrm);
end;
end loop;
end;
one better approach is to create a error handler Package/Procedure which will write it into a table and call it from the function, this way all the errors will be captured in a Oracle table.
--- untested -- You can create other columns to capture the function name, date, and other details in the error table.
PROCEDURE SP_ERROR_INS_ERR_COMMON (n_ERR_CODE NUMBER, c_ERR_SOURCE VARCHAR2, n_ERR_LINE NUMBER, c_ERR_DESC VARCHAR2, C_USER_COMMENT VARCHAR2 ) IS
n_Log_Id NUMBER;
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
n_Log_Id := 0;
INSERT INTO ERROR_LOG_COMMON
(ERROR_CODE, ERROR_SOURCE, ERROR_LINE, ERROR_DESCRIPTION, USER_COMMENT)
VALUES
(n_ERR_CODE, c_ERR_SOURCE, n_ERR_LINE, c_ERR_DESC, C_USER_COMMENT
);
COMMIT;
raise_application_error( -20001,SUBSTR(SQLERRM, 1, 200));
END SP_ERROR_INS_ERR_COMMON;
In your function you can call the error
EXCEPTION
WHEN OTHERS
THEN
vn_errcode := SQLCODE;
vc_errmsg := SUBSTR (SQLERRM, 1, 4000);
sp_error_ins_err_common(vn_ErrCode,
'SP_RP_DIM_COMPARE', NULL, vc_ErrMsg, substr('batch_id ' || g_BATCH_ID ||
l_str_err_msg,1,4000) );
RAISE;

execution flow of program when encounter exception oracle PLSQL

when we encounter an exception , the pointer will move to the exception part and if exception is handled will pointer come back or it move to the next part.?????
case 1: system defined exception
case 2: user defined exception
DECLARE
var_dividend NUMBER := 24;
var_divisor NUMBER := 0;
var_result NUMBER;
exception_div_zero EXCEPTION;
BEGIN
IF var_divisor = 0
THEN
RAISE exception_div_zero;
END IF;
var_result := var_dividend / var_divisor;
dbms_output.put_line(var_result);
EXCEPTION
WHEN exception_div_zero THEN
dbms_output.put_line(var_result);
END;
i want to know when the the exception encounter
after executing exception part will pointer come back to the next statement or it just exist the program.??enter code here
From the Oracle docs -
After an exception handler runs, control transfers to the next statement of the enclosing block. If there is no enclosing block, then:
If the exception handler is in a subprogram, then control returns to the invoker, at the statement after the invocation.
If the exception handler is in an anonymous block, then control transfers to the host environment (for example, SQL*Plus)
No, you don't go back to where you where. Rather the code keeps going after the exception handling.
Check this test out:
begin
dbms_output.put_line('One');
<<inner_one>>
begin
raise no_data_found;
dbms_output.put_line('Two');
exception
when no_data_found then
dbms_output.put_line('Three');
end inner_one;
dbms_output.put_line('Four');
raise no_data_found;
dbms_output.put_line('Five');
exception
when no_data_found then
dbms_output.put_line('Six');
end;
The output is:
One
Three
Four
Six
So Oracle's version of Try / Catch is to use anonymous blocks inside your blocks. You can nest blocks 255 times, which is a lot..
Example of using sub-block to parse a date string, if it fails, use current date/time.:
declare
l_date date;
begin
-- some code
-- parse date
begin
l_date := to_date(:input1, 'yyyy-mm-dd hh24:mi:ss');
exception
when others then
l_date := sysdate;
end;
--some more code
end;
Regards
Olafur

Identify when a function is executed in a SQL Query or in a PL/SQL procedure

Is there any way to identify when a pl/sql function is executed in SQL Query and when is executed in a procedure or PL/SQL anonymous block? (I don't want to pass any parameter for manual identification)
The main reason I need that is when a function is executed in a SQL query I wouldn't like to raise an exception in case of failure, I would be satisfied just with a returned value NULL. But the same function when is executed in pl/sql script I want to raise exception.
Thank you in advance.
Why don't you add a parameter to the function to indicate whether or not to throw an exception/return null? When you call the function you can choose the behaviour you need.
create or replace function do_something(p_parameter1 < some_type >
,p_raise_exception varchar2 default 'Y') return < sometype > is
begin
--.. calculating .. .
return result;
exception
when others then
if p_raise_exception is 'Y'
then
raise;
else
return null;
end if;
end;
Alternatively owa_util seems to provide some functionality you can use.
create or replace function do_something(p_parameter1 < some_type >) return < sometype > is
l_owner varchar2(100);
l_name varchar2(100);
l_lineno number;
l_caller_t varchar2(100);
begin
--.. calculating .. .
return result;
exception
when others then
owa_util.who_called_me(l_owner, l_name, l_lineno, l_caller_t)
-- who called me result seems empty when called from sql.
if l_owner is not null
then
raise;
else
return null;
end if;
end;
Of course :
Hiding all errors is bad practise
Well, looking around I found that there is a hack available:
The exception NO_DATA_FOUND isn't propagated when you call PL/SQL in SQL. So you can use this to "return null" instead of get an exception when calling it from SQL:
create or replace function f
return int as
begin
raise no_data_found;
return 1;
end f;
/
select f from dual;
F
null;
declare
v integer;
begin
v := f;
end;
Error report -
ORA-01403: no data found

NO_DATA_FOUND exception not thrown when used in SELECT INTO

I noticed strange behaviour of NO_DATA_FOUND exception when thrown from function used in PLSQL.
Long story short - it does propagate from function when using assignment, and does not propagate (or is handled silently somewhere in between) when used in SELECT INTO.
So, given function test_me throwing NO_DATA_FOUND exception, when invoked as:
v_x := test_me(p_pk);
It throws an exception, while when invoked as:
SELECT test_me(p_pk) INTO v_x FROM dual;
it does not throw exception. This does not occur with other exceptions. Below You can find my test examples.
Could somebody please explain to me this behaviour?
set serveroutput on;
CREATE OR REPLACE FUNCTION test_me(p_pk NUMBER) RETURN NVARCHAR2
IS
v_ret NVARCHAR2(50 CHAR);
BEGIN
BEGIN
SELECT 'PYK' INTO v_ret FROM dual WHERE 1 = 1/p_pk;
EXCEPTION WHEN NO_DATA_FOUND THEN
dbms_output.put_line(chr(9)||chr(9)||chr(9)||' (test_me NO_DATA_FOUND handled and rerised)');
RAISE;
END;
RETURN v_ret;
END;
/
DECLARE
v_x NVARCHAR2(500 CHAR);
v_pk NUMBER;
PROCEDURE test_example(p_pk NUMBER)
IS
BEGIN
BEGIN
dbms_output.put_line(chr(9)||chr(9)||'Test case 1: Select into.');
SELECT test_me(p_pk) INTO v_x FROM dual;
dbms_output.put_line(chr(9)||chr(9)||'Success: '||NVL(v_x,'NULL RETURNED'));
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line(chr(9)||chr(9)||'Failure: NO_DATA_FOUND detected');
WHEN OTHERS THEN
dbms_output.put_line(chr(9)||chr(9)||'Failure: '||SQLCODE||' detected');
END;
dbms_output.put_line(' ');
BEGIN
dbms_output.put_line(chr(9)||chr(9)||'Test case 2: Assignment.');
v_x := test_me(p_pk);
dbms_output.put_line(chr(9)||chr(9)||'Success: '||NVL(v_x,'NULL RETURNED'));
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line(chr(9)||chr(9)||'Failure: NO_DATA_FOUND detected');
WHEN OTHERS THEN
dbms_output.put_line(chr(9)||chr(9)||'Failure: '||SQLCODE||' detected');
END;
END;
BEGIN
dbms_output.put_line('START');
dbms_output.put_line(' ');
dbms_output.put_line(chr(9)||'Example 1: Function throws some exception, both cases throws exception, everything is working as expected.');
test_example(0);
dbms_output.put_line(' ');
dbms_output.put_line(chr(9)||'Example 2: Query returns row, there is no exceptions, everything is working as expected.');
test_example(1);
dbms_output.put_line(' ');
dbms_output.put_line(chr(9)||'Example 3: Query inside function throws NO_DATA_FOUND, strange things happen - one case is throwing exception, the other is not.');
test_example(2);
dbms_output.put_line(' ');
dbms_output.put_line('END');
END;
/
DROP FUNCTION test_me;
A minimal example is:
CREATE FUNCTION raise_exception RETURN INT
IS
BEGIN
RAISE NO_DATA_FOUND;
END;
/
If you do:
SELECT raise_exception
FROM DUAL;
You will get a single row containing a NULL value - Ask Tom states:
it has ALWAYS been that way
and then followed up with:
no_data_found is not an error - it is an "exceptional condition". You, the programmer, decide if something is an error by catching the exceptional condition and handling it (making it be "not an error") or ignoring it (making it be an error).
in sql, no data found quite simply means "no data found", stop.
Under the covers, SQL is raising back to the client application "hey buddy -- no_data_found". The
client in this case says "ah hah, no data found means 'end of data'" and stops.
So the exception is raised in the function and the SQL client sees this and interprets this as there is no data which is a NULL value and "handles" the exception.
So
DECLARE
variable_name VARCHAR2(50);
BEGIN
SELECT raise_exception
INTO variable_name
FROM DUAL
END;
/
Will succeed as the DUAL table has a single row and the exception from the function will be handled (silently) and the variable will end up containing a NULL value.
However,
BEGIN
DBMS_OUTPUT.PUT_LINE( raise_exception );
END;
/
The exception is this time being passed from the function to a PL/SQL scope - which does not handle the error and passes the exception to the exception handler block (which does not exist) so then gets passed up to the application scope and terminates execution of the program.
And Ask Tom states:
Under the covers, PLSQL is raising back to the client application "hey -- no_data_found. The client in this case says "uh-oh, wasn't expecting that from PLSQL -- sql sure, but not PLSQL. Lets print out the text that goes with this exceptional condition and continue on"
You see -- it is all in the way the CLIENT interprets the ORA-xxxxx message. That message, when raised by SQL, is interpreted by the client as "you are done". That message, when raised by PLSQL and not handled by the PLSQL programmer, is on the other hand interpreted as "a bad thing just happened"
Both PLSQL and SQL actually do the same thing here. It is the CLIENT that is deciding to do something different.
Now, if we change the function to raise a different exception:
CREATE OR REPLACE FUNCTION raise_exception RETURN INT
IS
BEGIN
RAISE ZERO_DIVIDE;
END;
/
Then both:
SELECT raise_exception
FROM DUAL;
and:
BEGIN
DBMS_OUTPUT.PUT_LINE( raise_exception );
END;
/
do not know how to handle the exception and terminate with ORA-01476 divisor is equal to zero.

wrong number or types of arguments in call (while calling a procedure/function)

If I want to catch this error using exception handling, what are the things that I need to take care of?
wrong number or types of arguments in call (while calling a
procedure/function)
I trying was in different way. Could you please explain. I have a function:
create or replace function test5(v varchar2) return varchar as
begin
execute immediate 'begin sweet.g:=:v;end;'
using in v;
return sweet.g;
exception
when others then
return sqlcode||' '||sqlerrm;
end test5;
And a package spec and body:
create or replace package SWEET as
function c ( v varchar2,V2 VARCHAR2) return varchar2;
g varchar(100);
end;
/
create or replace package body SWEET as
function c(v varchar2, V2 varchar2) return varchar2 as
begin
return v||'hi'|| V2;
end c;
end;
/
when I execute the statement below, I was not able to catch 'wrong number or type of arguments'
select test5(sweet.c(,'hello')) from dual;
You should be able to get most of the answers in the PL/SQL manual, but when you are trying to trap an error that isn't one of the predefined ones you have to do something like:
DECLARE
deadlock_detected EXCEPTION;
PRAGMA EXCEPTION_INIT(deadlock_detected, -60);
BEGIN
... -- Some operation that causes an ORA-00060 error
EXCEPTION
WHEN deadlock_detected THEN
-- handle the error
END;
replacing -60 with your actual error, and deadlock_detected with whatever you wish to call it.
Let's say you have a procedure that takes in two numbers as arguments and outputs them:
create procedure testProc (p_param1 in number, p_param2 in number) is
begin
dbms_output.put_line('params: ' || p_param1 || ' ' || p_param2);
end;
If you execute this:
begin
testProc(13,188);
end;
You get output of: params: 13 188
If you do this:
begin
testProc(13);
exception when others then
dbms_output.put_line('SQLERRM: ' || SQLERRM);
end;
You get an error: PLS-00306: wrong number or types of arguments in call to 'TESTPROC'
To prevent this and catch the error, you can use dynamic SQL:
declare
v_sql varchar2(50);
v_result number;
begin
v_sql := 'begin testProc(13); end;';
execute immediate v_sql into v_result;
exception
when others then
dbms_output.put_line('SQLERRM: ' || SQLERRM);
end;
That will execute, and the error message will be displayed to dbms_output. In the when others then block you can write any logic you want for what should happen at that point.