Exception Handling - WHEN OTHERS
Good Day to All,
When i am running a procedure in TOAD-Expert... it says below message.
*'Avoid using a WHEN OTHERS clause in an exception section without any other specific handlers.'*
PROCEDURE...
IS
BEGIN
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
-- Checking whether cursor is open
IF cur%ISOPEN THEN
CLOSE cur;
END IF;
UPDATE TABLE
SET COL..
WHERE ...
COMMIT;
RAISE;
END procedure;
The manner in which you are dealing with the exception is not wrong. Your handler does a couple of things:
- rollbacks the existing transaction as failed
- attempts resource protection (guard against resource leakage)
- logs the error
- re-raises the exception
None of these are invalid actions when dealing with an exception.
A suggestion though - move the UPDATE out of the exception and create a procedure that performs the logging for you (as an autonomous transaction). This way you have a reusable logging code unit that can be called from anywhere in your code.
Resource protection for explicit cursors are also not that critical in PL/SQL - as cursor handles that go out of scope are automatically released. The exception being a ref cursor handle. Of course, you need to resource protect other handles (like socket and file handles). And seeing that PL/SQL does not offer resource protection blocks, the only alternative is to use the "+when OTHERS+" exception handler for that.
Similar Messages
-
Utl_file - exception handling when inserted in bulk.
Hi,
I am using Oracle 10gR2. I wanted to write data to a file. Due to huge number of records, I am collecting them into a collection, traversing e collection, appending the values in collection to a varchar variable with new line in a loop.If the array size is say 50, I will have 50 values in the Vatchar variable separated by CHR(10). and I will insert the variable using UTL_FILE.PUT so that 50 lines will be inserted with values into the file.
Now my query is if any one among those 50 values gives an exception, I feel all the 50 values can't be loaded. Please suggest exception handling in this case.
Regards,
Naveen Kumar.C.
Edited by: Naveen Kumar C on Sep 17, 2009 5:23 PMYou could use a CLOB in conjunction with UTL_FILE to write it out 32K at a time...
SQL> ed
Wrote file afiedt.buf
1 DECLARE
2 l_file UTL_FILE.FILE_TYPE;
3 l_clob CLOB;
4 l_buffer VARCHAR2(32767);
5 l_amount BINARY_INTEGER := 32767;
6 l_pos INTEGER := 1;
7 BEGIN
8 BEGIN
9 SELECT dbms_xmlgen.getxmltype('select * from emp natural join dept').getclobval()
10 INTO l_clob
11 FROM dual;
12 EXCEPTION
13 WHEN NO_DATA_FOUND THEN
14 RETURN;
15 END;
16 l_file := UTL_FILE.fopen('TEST_DIR', 'Sample2.txt', 'w', 32767);
17 LOOP
18 DBMS_LOB.read (l_clob, l_amount, l_pos, l_buffer);
19 UTL_FILE.put(l_file, l_buffer);
20 l_pos := l_pos + l_amount;
21 END LOOP;
22 EXCEPTION
23 WHEN NO_DATA_FOUND THEN -- occurs when end of CLOB reached
24 UTL_FILE.fclose(l_file);
25 WHEN OTHERS THEN
26 DBMS_OUTPUT.put_line(SQLERRM);
27 UTL_FILE.fclose(l_file);
28* END;
SQL> /
PL/SQL procedure successfully completed.
SQL> -
Exception handling when no execuble bindings available in PageDefinition?
Currently I'm showcasing a simple authentication example to one of our clients. The example consists of the following :
* a simple AuthenticationFilter setup in my web.xml
* a simple (V1 ... not V2) DataAction with a modelReference property pointing to the correct pageModel.
The pageModel looks like this :
<?xml version="1.0" encoding="UTF-8" ?>
<pageDefinition xmlns="http://xmlns.oracle.com/adfm/uimodel"
version="10.1.3.36.73" id="indexPageDef"
Package="my.demo.package.pageDefs">
</pageDefinition>
As you can see ... it does not contain any executable bindings.
The DataAction has a "onLogon(DataActionContext ctx)" method which calls out to a method on my ApplicationModule (pretty similar to the Jheadstart authentication example). The method gets actually called and it performs the authentication perfectly. BUT .. when (for example) the username is not correct, it will throw a JboException.
When I try to login again (this time with the correct credentials) and no (new) exceptions are thrown, the old exception is still on the stack ! !
I tried forcing a bindingContainer.resetInputState() but that didn't help. After a period of digging in the source code I found out the following :
// oracle.adf.model.binding.DCBindingContainer
public void resetInputState() {
// other code
if (mExecutables == null)
return;
// other code
mExcs = null;
Some extra info : mExcs points to an ArrayList which contains the exceptions in the bindingcontainer. mExecutables point to a HashMap which contains the executable bindings in the bindingcontainer (~PageDef).
In other words : if the PageDef does not contain any executable bindings, the stack of exceptions is not reset. Which in my case is what's happening.
If I change the code of de DCBindingContainer to the following :
public void resetInputState() {
// other code
if (mExecutables == null)
// could not be sooner, because it is used later on...
mExcs = null;
return;
// other code
mExcs = null;
If I run my demo again I see that the stack of exceptions is actually cleared even though I do not have any executable bindings in my PageDef.
So, my question is : is it correct behaviour that resetInputState() does not clear the exceptions if I have an empty PageDefinition ?** bump **
-
Exception Handling when calling a PHP Webservice
I followed a great tutorial on setting calling PHP services from ABAP ([Accessing arbitrary databases from within ABAP using a PHP data hub and web services|Accessing arbitrary databases from within ABAP using a PHP data hub and web services]). Unfortunately I'm getting occassional CX_AI_SYSTEM_FAULT exceptions and I don't know how to handle them gracefully.
I'm calling the web service ABAP code from an RFC function which for some reason doesn't allow TRY/CATCH statements (I get a message saying "During RFC/update, no exception classes can be used".)
I'd be happy enough just to ignore the error since it's currently dumping users out of order entry.
To make matters more complicated, I can't TRY/CATCH my own RFC since I'm calling it from GuiXT
I'd really appreciate help on this; I'm pretty stumped.
Thanks,
LeeWell, to answer my own question, I found an ugly workaround.
Change attribute from "Remote-enabled" to "Normal Function", add the TRY/CATCH logic. Then call this function from the "real" RFC.
Off to program like it's 1979!
Lee -
Mediator exception handling when no data found in database
hi Guys,
I am using DB adapter in a composite and using a mediator to invoke them, however not getting how to send the response back,
in case there is NO_DATA_FOUND error.
waiting for response
thanks
YatanYatan
As far as i know a DB adapter will not throw no_data_found exception if it is not able to get rows from database it will just initialize the output variable with null. But yes in case of call to procedure or function it may cause that you should handle then and there only.
Let us know what exactly is the issue you are facing.
Thanks
AJ -
Exception handling when invoke ejb
Hi,
I call ejb like this:
try {
MyBeanHome beanHome = .. //jndi lookup
MyBean bean = beanHome .create();
HashMap h = bean.chargeFee(data);
bean.remove();
} catch (
}there are a lot exceptions: NamingException, CreationException, RemoteException, RemoveException (I don't have application exception).
I am thinking I catch the RemoveException first, since it happened after the chargeFee is called, and chargeFee is already been executed, so I deal it differently with the other Exceptions, since they heppend before or during the chargeFee executed, I treat it as not been executed.
Is it the right way to handle the exceptions? ThanksIt's difficult to answer you question because the intent is not known.
I would suggest to write down all possible exceptions and the actions to be taken. Try to pass on as many exceptions as possible to the client. I know I might be getting a lot for flake for this statement but catching too many exception makes the code look complicated. If you don't know what to do with an exception then just don't catch it.
If Pet Store example is complicated for you then try looking at Avitek Medical records example that comes bundled with BEA weblogic 8.1. You can install it for free and the example is just great.
- Roger -
How to get a 'when others' exception raised.
the 'when others' exception is raised usualy after a error occurs, but when does this actually occur? could some1 give an example??
usually some error occurs and then a inbuilt exception is raised. but 'others' exception never seems to take place?The OTHERS handler takes control when the exception is not handled by any previous handlers.
Here, we'll try to divide by zero. The no_data_found handler does not handle this error so control passes to the OTHERS section:
sql>declare
2 n number;
3 begin
4 n := 1/0;
5 exception
6 when no_data_found then
7 dbms_output.put_line( 'no data found exception' );
8 when others then
9 dbms_output.put_line( 'when others exception' );
10 end;
11 /
when others exception
PL/SQL procedure successfully completed.Now, we'll try an operation which will raise the no_data_found exception. Here the ndf handler does handle the error and control never passes to the OTHERS section:
sql>declare
2 n number;
3 begin
4 select 0
5 into n
6 from dual
7 where dummy is null;
8 exception
9 when no_data_found then
10 dbms_output.put_line( 'no data found exception' );
11 when others then
12 dbms_output.put_line( 'when others exception' );
13 end;
14 /
no data found exception
PL/SQL procedure successfully completed. -
Exception When Others question
I have the following section of code where the v_script variable is a sql statement:
EXECUTE IMMEDIATE v_script ;
COMMIT ;
EXCEPTION WHEN OTHERS THEN
ROLLBACK ;
My question is, if v_script fails, does it hit the COMMIT? Or does it skip it and go to the EXCEPTION line?
Thanks for the help,
ivalum21Hi,
The column COLR doesn't exist in table TEST.
Connected to Oracle Database 10g Enterprise Edition Release 10.2.0.1.0
Connected as hr
SQL>
SQL> SET SERVEROUTPUT ON
SQL> DECLARE
2 v_sql VARCHAR2(4000);
3 BEGIN
4 v_sql := 'INSERT INTO TEST(COLR) VALUES (1)';
5 EXECUTE IMMEDIATE v_sql;
6 dbms_output.put_line('Commit');
7 COMMIT;
8 EXCEPTION
9 WHEN OTHERS THEN
10 ROLLBACK;
11 dbms_output.put_line('When others exception');
12 END;
13 /
When others exception
PL/SQL procedure successfully completed
SQL> Regards,
Edited by: Walter Fernández on Dec 16, 2008 1:27 PM - Adding more text... -
PL/SQL 101 : Exception Handling
Frequently I see questions and issues around the use of Exception/Error Handling in PL/SQL. More often than not the issue comes from the questioners misunderstanding about how PL/SQL is constructed and executed, so I thought I'd write a small article covering the key concepts to give a clear picture of how it all hangs together. (Note: the examples are just showing examples of the exception handling structure, and should not be taken as truly valid code for ways of handling things)
Exception Handling
Contents
1. Understanding Execution Blocks (part 1)
2. Execution of the Execution Block
3. Exceptions
4. Understanding Execution Blocks (part 2)
5. How to continue exection of statements after an exception
6. User defined exceptions
7. Line number of exception
8. Exceptions within code within the exception block
1. Understanding Execution Blocks (part 1)
The first thing that one needs to understand is almost taking us back to the basics of PL/SQL... how a PL/SQL execution block is constructed.
Essentially an execution block is made of 3 sections...
+---------------------------+
| Declaration Section |
+---------------------------+
| Statements Section |
+---------------------------+
| Exception Section |
+---------------------------+
The Declaration section is the part defined between the PROCEDURE/FUNCTION header or the DECLARE keyword (for anonymous blocks) and the BEGIN keyword. (Optional section)
The Statements section is where your code goes and lies between the BEGIN keyword and the EXCEPTION keyword (or END keyword if there is no EXCEPTION section). (Mandatory section)
The Exception section is where any exception handling goes and lies between the EXCEPTION keyword at the END keyword. (Optional section)
Example of an anonymous block...
DECLARE
.. declarative statements go here ..
BEGIN
.. code statements go here ..
EXCEPTION
.. exception handlers go here ..
END;
Example of a procedure/function block...
[CREATE OR REPLACE] (PROCEDURE|FUNCTION) <proc or fn name> [(<parameters>)] [RETURN <datatype>] (IS|AS)
.. declarative statements go here ..
BEGIN
.. code statements go here ..
EXCEPTION
.. exception handlers go here ..
END;
(Note: The same can also be done for packages, but let's keep it simple)
2. Execution of the Execution Block
This may seem a simple concept, but it's surprising how many people have issues showing they haven't grasped it. When an Execution block is entered, the declaration section is processed, creating a scope of variables, types , cursors, etc. to be visible to the execution block and then execution enters into the Statements section. Each statment in the statements section is executed in turn and when the execution completes the last statment the execution block is exited back to whatever called it.
3. Exceptions
Exceptions generally happen during the execution of statements in the Statements section. When an exception happens the execution of statements jumps immediately into the exception section. In this section we can specify what exceptions we wish to 'capture' or 'trap' and do one of the two following things...
(Note: The exception section still has access to all the declared items in the declaration section)
3.i) Handle the exception
We do this when we recognise what the exception is (most likely it's something we expect to happen) and we have a means of dealing with it so that our application can continue on.
Example...
(without the exception handler the exception is passed back to the calling code, in this case SQL*Plus)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 begin
4 select ename
5 into v_name
6 from emp
7 where empno = &empno;
8 dbms_output.put_line(v_name);
9* end;
SQL> /
Enter value for empno: 123
old 7: where empno = &empno;
new 7: where empno = 123;
declare
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 4
(with an exception handler, we capture the exception, handle it how we want to, and the calling code is happy that there is no error for it to report)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 begin
4 select ename
5 into v_name
6 from emp
7 where empno = &empno;
8 dbms_output.put_line(v_name);
9 exception
10 when no_data_found then
11 dbms_output.put_line('There is no employee with this employee number.');
12* end;
SQL> /
Enter value for empno: 123
old 7: where empno = &empno;
new 7: where empno = 123;
There is no employee with this employee number.
PL/SQL procedure successfully completed.
3.ii) Raise the exception
We do this when:-
a) we recognise the exception, handle it but still want to let the calling code know that it happened
b) we recognise the exception, wish to log it happened and then let the calling code deal with it
c) we don't recognise the exception and we want the calling code to deal with it
Example of b)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 v_empno NUMBER := &empno;
4 begin
5 select ename
6 into v_name
7 from emp
8 where empno = v_empno;
9 dbms_output.put_line(v_name);
10 EXCEPTION
11 WHEN no_data_found THEN
12 INSERT INTO sql_errors (txt)
13 VALUES ('Search for '||v_empno||' failed.');
14 COMMIT;
15 RAISE;
16* end;
SQL> /
Enter value for empno: 123
old 3: v_empno NUMBER := &empno;
new 3: v_empno NUMBER := 123;
declare
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 15
SQL> select * from sql_errors;
TXT
Search for 123 failed.
SQL>
Example of c)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 v_empno NUMBER := &empno;
4 begin
5 select ename
6 into v_name
7 from emp
8 where empno = v_empno;
9 dbms_output.put_line(v_name);
10 EXCEPTION
11 WHEN no_data_found THEN
12 INSERT INTO sql_errors (txt)
13 VALUES ('Search for '||v_empno||' failed.');
14 COMMIT;
15 RAISE;
16 WHEN others THEN
17 RAISE;
18* end;
SQL> /
Enter value for empno: 'ABC'
old 3: v_empno NUMBER := &empno;
new 3: v_empno NUMBER := 'ABC';
declare
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at line 3
SQL> select * from sql_errors;
TXT
Search for 123 failed.
SQL>
As you can see from the sql_errors log table, no log was written so the WHEN others exception was the exception that raised the error to the calling code (SQL*Plus)
4. Understanding Execution Blocks (part 2)
Ok, so now we understand the very basics of an execution block and what happens when an exception happens. Let's take it a step further...
Execution blocks are not just a single simple block in most cases. Often, during our statements section we have a need to call some reusable code and we do that by calling a procedure or function. Effectively this nests the procedure or function's code as another execution block within the current statement section so, in terms of execution, we end up with something like...
+---------------------------------+
| Declaration Section |
+---------------------------------+
| Statements Section |
| . |
| +---------------------------+ |
| | Declaration Section | |
| +---------------------------+ |
| | Statements Section | |
| +---------------------------+ |
| | Exception Section | |
| +---------------------------+ |
| . |
+---------------------------------+
| Exception Section |
+---------------------------------+
Example... (Note: log_trace just writes some text to a table for tracing)
SQL> create or replace procedure a as
2 v_dummy NUMBER := log_trace('Procedure A''s Declaration Section');
3 begin
4 v_dummy := log_trace('Procedure A''s Statement Section');
5 v_dummy := 1/0; -- cause an exception
6 exception
7 when others then
8 v_dummy := log_trace('Procedure A''s Exception Section');
9 raise;
10 end;
11 /
Procedure created.
SQL> create or replace procedure b as
2 v_dummy NUMBER := log_trace('Procedure B''s Declaration Section');
3 begin
4 v_dummy := log_trace('Procedure B''s Statement Section');
5 a; -- HERE the execution passes to the declare/statement/exception sections of A
6 exception
7 when others then
8 v_dummy := log_trace('Procedure B''s Exception Section');
9 raise;
10 end;
11 /
Procedure created.
SQL> exec b;
BEGIN b; END;
ERROR at line 1:
ORA-01476: divisor is equal to zero
ORA-06512: at "SCOTT.B", line 9
ORA-06512: at line 1
SQL> select * from code_trace;
TXT
Procedure B's Declaration Section
Procedure B's Statement Section
Procedure A's Declaration Section
Procedure A's Statement Section
Procedure A's Exception Section
Procedure B's Exception Section
6 rows selected.
SQL>
Likewise, execution blocks can be nested deeper and deeper.
5. How to continue exection of statements after an exception
One of the common questions asked is how to return execution to the statement after the one that created the exception and continue on.
Well, firstly, you can only do this for statements you expect to raise an exception, such as when you want to check if there is no data found in a query.
If you consider what's been shown above you could put any statement you expect to cause an exception inside it's own procedure or function with it's own exception section to handle the exception without raising it back to the calling code. However, the nature of procedures and functions is really to provide a means of re-using code, so if it's a statement you only use once it seems a little silly to go creating individual procedures for these.
Instead, you nest execution blocks directly, to give the same result as shown in the diagram at the start of part 4 of this article.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure b (p_empno IN VARCHAR2) as
2 v_dummy NUMBER := log_trace('Procedure B''s Declaration Section');
3 begin
4 v_dummy := log_trace('Procedure B''s Statement Section');
5 -- Here we start another execution block nested in the first one...
6 declare
7 v_dummy NUMBER := log_trace('Nested Block Declaration Section');
8 begin
9 v_dummy := log_trace('Nested Block Statement Section');
10 select empno
11 into v_dummy
12 from emp
13 where empno = p_empno; -- Note: the parameters and variables from
parent execution block are available to use!
14 exception
15 when no_data_found then
16 -- This is an exception we can handle so we don't raise it
17 v_dummy := log_trace('No employee was found');
18 v_dummy := log_trace('Nested Block Exception Section - Exception Handled');
19 when others then
20 -- Other exceptions we can't handle so we raise them
21 v_dummy := log_trace('Nested Block Exception Section - Exception Raised');
22 raise;
23 end;
24 -- ...Here endeth the nested execution block
25 -- As the nested block handled it's exception we come back to here...
26 v_dummy := log_trace('Procedure B''s Statement Section Continued');
27 exception
28 when others then
29 -- We'll only get to here if an unhandled exception was raised
30 -- either in the nested block or in procedure b's statement section
31 v_dummy := log_trace('Procedure B''s Exception Section');
32 raise;
33* end;
SQL> /
Procedure created.
SQL> exec b(123);
PL/SQL procedure successfully completed.
SQL> select * from code_trace;
TXT
Procedure B's Declaration Section
Procedure B's Statement Section
Nested Block Declaration Section
Nested Block Statement Section
No employee was found
Nested Block Exception Section - Exception Handled
Procedure B's Statement Section Continued
7 rows selected.
SQL> truncate table code_trace;
Table truncated.
SQL> exec b('ABC');
BEGIN b('ABC'); END;
ERROR at line 1:
ORA-01722: invalid number
ORA-06512: at "SCOTT.B", line 32
ORA-06512: at line 1
SQL> select * from code_trace;
TXT
Procedure B's Declaration Section
Procedure B's Statement Section
Nested Block Declaration Section
Nested Block Statement Section
Nested Block Exception Section - Exception Raised
Procedure B's Exception Section
6 rows selected.
SQL>
You can see from this that, very simply, the code that we expected may have an exception was able to either handle the exception and return to the outer execution block to continue execution, or if an unexpected exception occurred then it was able to be raised up to the outer exception section.
6. User defined exceptions
There are three sorts of 'User Defined' exceptions. There are logical situations (e.g. business logic) where, for example, certain criteria are not met to complete a task, and there are existing Oracle errors that you wish to give a name to in order to capture them in the exception section. The third is raising your own exception messages with our own exception numbers. Let's look at the first one...
Let's say I have tables which detail stock availablility and reorder levels...
SQL> select * from reorder_level;
ITEM_ID STOCK_LEVEL
1 20
2 20
3 10
4 2
5 2
SQL> select * from stock;
ITEM_ID ITEM_DESC STOCK_LEVEL
1 Pencils 10
2 Pens 2
3 Notepads 25
4 Stapler 5
5 Hole Punch 3
SQL>
Now, our Business has told the administrative clerk to check stock levels and re-order anything that is below the re-order level, but not to hold stock of more than 4 times the re-order level for any particular item. As an IT department we've been asked to put together an application that will automatically produce the re-order documents upon the clerks request and, because our company is so tight-ar*ed about money, they don't want to waste any paper with incorrect printouts so we have to ensure the clerk can't order things they shouldn't.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 from stock s join reorder_level r on (s.item_id = r.item_id)
7 where s.item_id = p_item_id;
8 --
9 v_stock cur_stock_reorder%ROWTYPE;
10 begin
11 OPEN cur_stock_reorder;
12 FETCH cur_stock_reorder INTO v_stock;
13 IF cur_stock_reorder%NOTFOUND THEN
14 RAISE no_data_found;
15 END IF;
16 CLOSE cur_stock_reorder;
17 --
18 IF v_stock.stock_level >= v_stock.reorder_level THEN
19 -- Stock is not low enough to warrant an order
20 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
21 ELSE
22 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
23 -- Required amount is over-ordering
24 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
25 ELSE
26 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
27 -- Here goes our code to print the order
28 END IF;
29 END IF;
30 --
31 exception
32 WHEN no_data_found THEN
33 CLOSE cur_stock_reorder;
34 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
35* end;
SQL> /
Procedure created.
SQL> exec re_order(10,100);
Invalid Item ID.
PL/SQL procedure successfully completed.
SQL> exec re_order(3,40);
Stock has not reached re-order level yet!
PL/SQL procedure successfully completed.
SQL> exec re_order(1,100);
Quantity specified is too much. Max for this item: 70
PL/SQL procedure successfully completed.
SQL> exec re_order(2,50);
Order OK. Printing Order...
PL/SQL procedure successfully completed.
SQL>
Ok, so that code works, but it's a bit messy with all those nested IF statements. Is there a cleaner way perhaps? Wouldn't it be nice if we could set up our own exceptions...
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 from stock s join reorder_level r on (s.item_id = r.item_id)
7 where s.item_id = p_item_id;
8 --
9 v_stock cur_stock_reorder%ROWTYPE;
10 --
11 -- Let's declare our own exceptions for business logic...
12 exc_not_warranted EXCEPTION;
13 exc_too_much EXCEPTION;
14 begin
15 OPEN cur_stock_reorder;
16 FETCH cur_stock_reorder INTO v_stock;
17 IF cur_stock_reorder%NOTFOUND THEN
18 RAISE no_data_found;
19 END IF;
20 CLOSE cur_stock_reorder;
21 --
22 IF v_stock.stock_level >= v_stock.reorder_level THEN
23 -- Stock is not low enough to warrant an order
24 RAISE exc_not_warranted;
25 END IF;
26 --
27 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
28 -- Required amount is over-ordering
29 RAISE exc_too_much;
30 END IF;
31 --
32 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
33 -- Here goes our code to print the order
34 --
35 exception
36 WHEN no_data_found THEN
37 CLOSE cur_stock_reorder;
38 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
39 WHEN exc_not_warranted THEN
40 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
41 WHEN exc_too_much THEN
42 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
43* end;
SQL> /
Procedure created.
SQL> exec re_order(10,100);
Invalid Item ID.
PL/SQL procedure successfully completed.
SQL> exec re_order(3,40);
Stock has not reached re-order level yet!
PL/SQL procedure successfully completed.
SQL> exec re_order(1,100);
Quantity specified is too much. Max for this item: 70
PL/SQL procedure successfully completed.
SQL> exec re_order(2,50);
Order OK. Printing Order...
PL/SQL procedure successfully completed.
SQL>
That's better. And now we don't have to use all those nested IF statements and worry about it accidently getting to code that will print the order out as, once one of our user defined exceptions is raised, execution goes from the Statements section into the Exception section and all handling of errors is done in one place.
Now for the second sort of user defined exception...
A new requirement has come in from the Finance department who want to have details shown on the order that show a re-order 'indicator' based on the formula ((maximum allowed stock - current stock)/re-order quantity), so this needs calculating and passing to the report...
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
7 from stock s join reorder_level r on (s.item_id = r.item_id)
8 where s.item_id = p_item_id;
9 --
10 v_stock cur_stock_reorder%ROWTYPE;
11 --
12 -- Let's declare our own exceptions for business logic...
13 exc_not_warranted EXCEPTION;
14 exc_too_much EXCEPTION;
15 begin
16 OPEN cur_stock_reorder;
17 FETCH cur_stock_reorder INTO v_stock;
18 IF cur_stock_reorder%NOTFOUND THEN
19 RAISE no_data_found;
20 END IF;
21 CLOSE cur_stock_reorder;
22 --
23 IF v_stock.stock_level >= v_stock.reorder_level THEN
24 -- Stock is not low enough to warrant an order
25 RAISE exc_not_warranted;
26 END IF;
27 --
28 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
29 -- Required amount is over-ordering
30 RAISE exc_too_much;
31 END IF;
32 --
33 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
34 -- Here goes our code to print the order, passing the finance_factor
35 --
36 exception
37 WHEN no_data_found THEN
38 CLOSE cur_stock_reorder;
39 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
40 WHEN exc_not_warranted THEN
41 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
42 WHEN exc_too_much THEN
43 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
44* end;
SQL> /
Procedure created.
SQL> exec re_order(2,40);
Order OK. Printing Order...
PL/SQL procedure successfully completed.
SQL> exec re_order(2,0);
BEGIN re_order(2,0); END;
ERROR at line 1:
ORA-01476: divisor is equal to zero
ORA-06512: at "SCOTT.RE_ORDER", line 17
ORA-06512: at line 1
SQL>
Hmm, there's a problem if the person specifies a re-order quantity of zero. It raises an unhandled exception.
Well, we could put a condition/check into our code to make sure the parameter is not zero, but again we would be wrapping our code in an IF statement and not dealing with the exception in the exception handler.
We could do as we did before and just include a simple IF statement to check the value and raise our own user defined exception but, in this instance the error is standard Oracle error (ORA-01476) so we should be able to capture it inside the exception handler anyway... however...
EXCEPTION
WHEN ORA-01476 THEN
... is not valid. What we need is to give this Oracle error a name.
This is done by declaring a user defined exception as we did before and then associating that name with the error number using the PRAGMA EXCEPTION_INIT statement in the declaration section.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
7 from stock s join reorder_level r on (s.item_id = r.item_id)
8 where s.item_id = p_item_id;
9 --
10 v_stock cur_stock_reorder%ROWTYPE;
11 --
12 -- Let's declare our own exceptions for business logic...
13 exc_not_warranted EXCEPTION;
14 exc_too_much EXCEPTION;
15 --
16 exc_zero_quantity EXCEPTION;
17 PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
18 begin
19 OPEN cur_stock_reorder;
20 FETCH cur_stock_reorder INTO v_stock;
21 IF cur_stock_reorder%NOTFOUND THEN
22 RAISE no_data_found;
23 END IF;
24 CLOSE cur_stock_reorder;
25 --
26 IF v_stock.stock_level >= v_stock.reorder_level THEN
27 -- Stock is not low enough to warrant an order
28 RAISE exc_not_warranted;
29 END IF;
30 --
31 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
32 -- Required amount is over-ordering
33 RAISE exc_too_much;
34 END IF;
35 --
36 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
37 -- Here goes our code to print the order, passing the finance_factor
38 --
39 exception
40 WHEN exc_zero_quantity THEN
41 DBMS_OUTPUT.PUT_LINE('Quantity of 0 (zero) is invalid.');
42 WHEN no_data_found THEN
43 CLOSE cur_stock_reorder;
44 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
45 WHEN exc_not_warranted THEN
46 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
47 WHEN exc_too_much THEN
48 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
49* end;
SQL> /
Procedure created.
SQL> exec re_order(2,0);
Quantity of 0 (zero) is invalid.
PL/SQL procedure successfully completed.
SQL>
Lastly, let's look at raising our own exceptions with our own exception numbers...
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
7 from stock s join reorder_level r on (s.item_id = r.item_id)
8 where s.item_id = p_item_id;
9 --
10 v_stock cur_stock_reorder%ROWTYPE;
11 --
12 exc_zero_quantity EXCEPTION;
13 PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
14 begin
15 OPEN cur_stock_reorder;
16 FETCH cur_stock_reorder INTO v_stock;
17 IF cur_stock_reorder%NOTFOUND THEN
18 RAISE no_data_found;
19 END IF;
20 CLOSE cur_stock_reorder;
21 --
22 IF v_stock.stock_level >= v_stock.reorder_level THEN
23 -- Stock is not low enough to warrant an order
24 [b]RAISE_APPLICATION_ERROR(-20000, 'Stock has not reached re-order level yet!');[/b]
25 END IF;
26 --
27 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
28 -- Required amount is over-ordering
29its nice article, have put up this one the blog
site,Nah, I don't have time to blog, but if one of the other Ace's/Experts wants to copy it to a blog with reference back to here (and all due credit given ;)) then that's fine by me.
I'd go for a book like "Selected articles by OTN members" or something. Does anybody have a list of links of all those mentioned articles?Just these ones I've bookmarked...
Introduction to regular expressions ... by CD
When your query takes too long ... by Rob van Wijk
How to pipeline a function with a dynamic number of columns? by ascheffer
PL/SQL 101 : Exception Handling by BluShadow -
Exception Handling In BPEL By using Catch Blocks or Fault Policies Or Both
I have a confusion regarding
Exception handling :
When Should i go for 1)Catch Block (Remote , or binding ) in bpel for exception handling .
2)Fault Policy , Fault binding.xml
Currently iam using catch blocks , but even fault policy is good , but can i use both...
Currently in My bpel ,when any error occurs i have to send a error notification by Email .
Currently i have exposed the email service which shuts emails and write a file with errored Message.
Hence if any error i will catch i in a parent BPEL, i will just invoke the above email, service .
So anybody can help me by giving the suggestion how to go for the best approach
Edited by: anantwag on Mar 23, 2011 6:31 AMCurrently in My bpel ,when any error occurs i have to send a error notification by Email .
Currently i have exposed the email service which shuts emails and write a file with errored Message.Seeing your use case I will suggest you to use fault handling framework (fault policy). Fault handling framework should be used where you need generic error handling framework which handles all the faults occured in any composite component. Generally BPEL catch block should be used to propagate error info/fault back to the client/to fault handling framework or to consume an error
Regards,
Anuj -
Exception handling in ODI - common exception handling framework
Hi,
I need to come up with a common exception handling framework in an environment where ESB and ODI are being used for interfacing and ELT operations. I am of the opinion that
1. I am not able to find any documentation wrt exception handling when ODI is used? Can some one help me with some pointers?
2, When I come up with a common exception handling framework using BPEL, will I be able to invoke the same from ODI.
Thanks,
MaheshThanks for the reply Allan. I haven't used BusinessWorks.
I did go through this thread before and here's my understanding.
1. ESB provides the ability of error handling (client management API) but not the exception handling i.e. I can't redirect the flow in case there is an exception in my primary flow. Am I right with my understanding?
2. Error handling ability of ESB is limited to retryable exceptions viz-a-viz asynchrounous ESB processes (e.g. database listener not up) where in the process can be retried. Am I right here?
Thanks,
Mahesh -
Exception handling with fault message type not working
Hi,
I have a sync proxy to proxy scenario and I have created a fault MT and specified in the outbound and Inbound service interface...
*In Inbound proxy I have the following code--*......
RAISE EXCEPTION TYPE z_cx_test_fault
EXPORTING
standard = l_standard_data.
In the sender side abap code which calls the outbound proxy I have the follwing code -
CATCH cx_ai_system_fault INTO lo_cx_ai_system_fault.
txt = lo_cx_ai_system_fault->get_text( ).
WRITE txt.
CATCH z_cx_test_fault INTO lo_cx_test_fault.
txt = lo_cx_standard_message_fault->get_text( ).
WRITE txt.
CATCH cx_ai_application_fault INTO lo_cx_ai_application_fault.
txt = lo_cx_ai_application_fault->get_text( ).
WRITE txt.
when i test the inbound proxy separately I get the custom fault message properly...
however when i run the proxy to proxy sync scenario and the custom exceptionz_cx_test_fault is raised inside the receiver proxy .......control goes to CATCH cx_ai_application_fault and not CATCH z_cx_test_fault .
I understand that cx_ai_application_fault is the super class of all the exception class but why does control go to its exception handling when a custom exception is raised...
Edited by: hema T on Feb 26, 2012 1:16 PM
Edited by: hema T on Feb 26, 2012 1:17 PMHi
I tried changing the sequence also but it did not work...
I can see an appropriate response coming from the receiver in SXMB_MONI of PI...this response has the "fault response "
"fault detail" data that I want.....however when the control goes to the sender why does it go to CATCH CX_AI_APPLICATION_FAULT and not not my CATCH z_cx_test_fault .
My observation - If I change the scenario to SOAP to Proxy sync..then the sender SOAP client gets the appropriate custom fault message back.
Edited by: hema T on Feb 27, 2012 1:17 PM
Edited by: hema T on Feb 27, 2012 1:17 PM -
Hi All,
Below is my pl/sql block.
My question is why PL/SQL cannot handle the exception, and instead the exception is propagated to SQL Plus?
I'm using oracle 8.1.7.0
TIA.
SQL> begin
2 select * from emp;
3 exception
4 when others then
5 dbms_output.put_line('ERROR !!!');
6
7 end;
8 /
select * from emp;
ERROR at line 2:
ORA-06550: line 2, column 3:
PLS-00428: an INTO clause is expected in this SELECT statement
ORA-06550: line 2, column 3:
PL/SQL: SQL Statement ignoredThere is no runtime exception to handle because this is not even a valid PL/SQL anonymous block. Every SELECT statement in PL/SQL must be either SELECTed INTO a variable or exist as part of a cursor.
If you explain what you are trying to do here, we can offer some suggestions.
Simple SELECT INTO example:
declare
v_empno emp.empno%type;
begin
select empno
into v_empno
from emp
where empno = 1;
dbms_output.put_line(v_empno);
exception
when no_data_found then
dbms_output.put_line('Employee number 1 does not exist');
end;
/ -
Exception handling - Common exception handling framework
Hi,
I need to come up with a common exception handling framework in an environment where ESB and ODI are being used for interfacing and ELT operations. I am of the opinion that
1. A generic exception handling framework can be built using BPEL and can be invoked from ESB. Is my understanding correct?
2. Are there any ways that we can build this framework using ESB itself? I opinion that it's not possible as there is no concept of try-catch?
3. I am not able to find any documentation wrt exception handling when ODI is used? Can some one help me with some pointers?
4, When I come up with a common exception handling framework, will I be able to invoke the same from ODI.
Thanks,
MaheshThanks for the reply Allan. I haven't used BusinessWorks.
I did go through this thread before and here's my understanding.
1. ESB provides the ability of error handling (client management API) but not the exception handling i.e. I can't redirect the flow in case there is an exception in my primary flow. Am I right with my understanding?
2. Error handling ability of ESB is limited to retryable exceptions viz-a-viz asynchrounous ESB processes (e.g. database listener not up) where in the process can be retried. Am I right here?
Thanks,
Mahesh -
When Others not raised for Dynamic SQL occasionally
Hi All,
Please consider some part of my PL/SQL code below.
FOR rec IN cur_job_steps
LOOP
update_job_step_status(p_sector,
p_job_name,
rec.step_name,
'Running',
NULL,
SYSDATE,
NULL
-- Execute Job Step Function
EXECUTE IMMEDIATE 'BEGIN ' || rec.step_function || '; END;';
-- Set Job Step End Status
update_job_step_status(p_sector,
p_job_name,
rec.step_name,
'Successful',
NULL,
NULL,
SYSDATE
END LOOP;
EXCEPTION
WHEN OTHERS
THEN
ROLLBACK;
-- Set Job Failed Status
update_job_status(p_sector,
p_job_name,
'Failed',
'Could Not Complete DB Job: ' || SQLERRM,
NULL,
SYSDATE
-- Set Job Step Failed Status
END;
rec.step_function is a procedure without any "When Others" clause. When that exception occurs I am expecting the "When Others" clause of the calling procedure is not capturing it some times. Is there any limitation to this? Any info in this regards would be really useful.
Thanks in advance.
Best Regards
Srikanth TirandasCould not reproduce.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure my_proc
2 as
3 v_num number;
4 begin
5 v_num := 1 / 0;
6* end;
SQL> /
Procedure created.
SQL> ed
Wrote file afiedt.buf
1 begin
2 begin
3 execute immediate 'begin my_proc; end;' ;
4 end;
5 exception
6 when others then
7 dbms_output.put_line(sqlerrm);
8* end;
SQL> /
ORA-01476: divisor is equal to zero
PL/SQL procedure successfully completed.
Can you provide code for your function when it does not work ? It seems some "rec.step_function" are coded to handle exceptions and hence you don't get any in outer loop.
Maybe you are looking for
-
Report generation failed after migrated from 6i to 10g.
Hi All, i have migrated the 6i application to 10g. There was a report which was generated in .html format and saved to a remote server location. Now after migration to 10g,when i run the report through the URL ,It is still generated on the same remot
-
Hard drive and system recovery question - "No boot device"
I replaced a 320Gb - 5400 rpm drive that failed with a 750Gb - 7200 rpm drive. Using the HP System Recovery disks to reload the OS, once it goes through the restoration process the mb doesn't seem to recognize the hard drive and I get the "No Boot d
-
Your call cannot be connected pls. check your phone settings help plsss
your call cannot be connected pls. check your phone settings help plsss
-
Final Cut X 10.0.4 - cannot share a movie greater than 15 mins to youtube
So I just updated to 10.0.4 this morning. Open an existing project that is roughly 19 minutes long, which by the way I previously published to my YouTube account with no problem at all. Now Final Cut will not allow me to publish the video. I get an e
-
I bought an iPhone 5 from someone, how long does it take for his Apple ID to come off
I bought an iPhone 5s from someone second hand, he had put it back to factory settings but when I tried to use it it asked for his Apple ID and password, I contacted him to ask for him to delete his id from the phone, how long does it take after he d