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
29     

its 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

Similar Messages

  • Exception handling in  in insert statemnt

    i am inserting values in to a table in a procedure.for insert statemnt what are the possible exceptions that may occur.
    how to handle exceptions for that insert statement(other than when others)

    user639995 wrote:
    is there any possiblity to use if sql%rowcount = 0 then
    RAISE e1;
    like thisNot for an insert statement, no.
    sql%rowcount returns the number of rows effected by a DML statement.
    For any of the statements you can only check sql%rowcount after the DML statement successfully executes, and it will only return a 0 if no rows were effected by that DML statement e.g. if an update effected no rows or an insert ... select ... actually inserted no rows etc.
    If an exception occurs during a DML statement then execution will pass directly to the exception handler so you won't have the opportunity to test for sql%rowcount after the statement.
    You should have an exception handler for expected exceptions.
    If an exception is not expected then you should let your code raise it up so it is seen and not handled.
    example of defining exceptions for non-named error numbers...
    SQL> create table x (x number);
    Table created.
    SQL> insert into x values ('x');
    insert into x values ('x')
    ERROR at line 1:
    ORA-01722: invalid number
    SQL> set serverout on
    SQL> declare
      2    ex_not_number exception;
      3    pragma exception_init(ex_not_number, -1722);
      4  begin
      5    insert into x values (1);
      6    commit;
      7    insert into x values ('A');
      8    commit;
      9  exception
    10    when ex_not_number then
    11      dbms_output.put_line('An attempt to insert a value that is not a number was made.');
    12  end;
    13  /
    An attempt to insert a value that is not a number was made.
    PL/SQL procedure successfully completed.
    SQL> select * from x;
             X
             1
    SQL>Further details on exception handling here:
    [PL/SQL 101 : Exception Handling|http://forums.oracle.com/forums/thread.jspa?threadID=697262&tstart=50]

  • Why Exception Handling

    Hello All,
    I am new to PL/SQL and have this question.
    Why do we need exception handling? If some error occurs dont we want to stop execution of program so that we can see the error in the host environment or have it logged in an error table or written in a file before we correct the error and re-run the application. I am not able to clearly see why? Please help understand this.
    Thank you for time!

    user631936 wrote:
    Hello All,
    I am new to PL/SQL and have this question.
    Why do we need exception handling? If some error occurs dont we want to stop execution of program so that we can see the error in the host environment or have it logged in an error table or written in a file before we correct the error and re-run the application. I am not able to clearly see why? Please help understand this.
    Thank you for time!Exception handling lets the designed/developer choose how exceptions should be handled.
    Some exceptions may be expected under certain circumstances such as e.g. NO_DATA_FOUND, and you may want the application to continue processing regardless or continue processing in a different way if that condition is encountered. Other exceptions may require that some previous actions are reversed or rolled back on the database, so capturing them and dealing with that business process can be useful, before the exception is raised back to the calling code/application. Any exceptions that aren't expected and handled, should be RAISEd so that the calling code has the choice to deal with them or RAISE them further up until it get's to a stage where it is handled or the application itself reports the exception to the user.
    Capturing exceptions can of course be useful if you need to log any that occur as you can capture it, store information about it in a table/log file and then raise it to be handled or raised again as necessary.
    What is an absolute no-no in design and development terms is to include a WHEN OTHERS exception that does not raise the exception or notify the calling code/user in some way. This simply masks any exceptions that occur, especially the ones that are not expected, which are of course the ones that you really need to know about so you can fix the underlying issues.
    PL/SQL 101 : Exception Handling
    PL/SQL 101 : Exception Handling

  • PL/SQL 101 : Cursors and SQL Projection

    PL/SQL 101 : Cursors and SQL Projection
    This is not a question, it's a forum article, in reponse to the number of questions we get regarding a "dynamic number of columns" or "rows to columns"
    There are two integral parts to an SQL Select statement that relate to what data is selected. One is Projection and the other is Selection:-
    Selection is the one that we always recognise and use as it forms the WHERE clause of the select statement, and hence selects which rows of data are queried.
    The other, SQL Projection is the one that is less understood, and the one that this article will help to explain.
    In short, SQL Projection is the collective name for the columns that are Selected and returned from a query.
    So what? Big deal eh? Why do we need to know this?
    The reason for knowing this is that many people are not aware of when SQL projection comes into play when you issue a select statement. So let's take a basic query...
    First create some test data...
    create table proj_test as
      select 1 as id, 1 as rn, 'Fred' as nm from dual union all
      select 1,2,'Bloggs' from dual union all
      select 2,1,'Scott' from dual union all
      select 2,2,'Smith' from dual union all
      select 3,1,'Jim' from dual union all
      select 3,2,'Jones' from dual
    ... and now query that data...
    SQL> select * from proj_test;
             ID         RN NM
             1          1 Fred
             1          2 Bloggs
             2          1 Scott
             2          2 Smith
             3          1 Jim
             3          2 Jones
    6 rows selected.
    OK, so what is that query actually doing?
    To know that we need to consider that all queries are cursors and all cursors are processed in a set manner, roughly speaking...
    1. The cursor is opened
    2. The query is parsed
    3. The query is described to know the projection (what columns are going to be returned, names, datatypes etc.)
    4. Bind variables are bound in
    5. The query is executed to apply the selection and identify the data to be retrieved
    6. A row of data is fetched
    7. The data values from the columns within that row are extracted into the known projection
    8. Step 6 and 7 are repeated until there is no more data or another condition ceases the fetching
    9. The cursor is closed
    The purpose of the projection being determined is so that the internal processing of the cursor can allocate memory etc. ready to fetch the data into. We won't get to see that memory allocation happening easily, but we can see the same query being executed in these steps if we do it programatically using the dbms_sql package...
    CREATE OR REPLACE PROCEDURE process_cursor (p_query in varchar2) IS
      v_sql       varchar2(32767) := p_query;
      v_cursor    number;            -- A cursor is a handle (numeric identifier) to the query
      col_cnt     integer;
      v_n_val     number;            -- numeric type to fetch data into
      v_v_val     varchar2(20);      -- varchar type to fetch data into
      v_d_val     date;              -- date type to fetch data into
      rec_tab     dbms_sql.desc_tab; -- table structure to hold sql projection info
      dummy       number;
      v_ret       number;            -- number of rows returned
      v_finaltxt  varchar2(100);
      col_num     number;
    BEGIN
      -- 1. Open the cursor
      dbms_output.put_line('1 - Opening Cursor');
      v_cursor := dbms_sql.open_cursor;
      -- 2. Parse the cursor
      dbms_output.put_line('2 - Parsing the query');
      dbms_sql.parse(v_cursor, v_sql, dbms_sql.NATIVE);
      -- 3. Describe the query
      -- Note: The query has been described internally when it was parsed, but we can look at
      --       that description...
      -- Fetch the description into a structure we can read, returning the count of columns that has been projected
      dbms_output.put_line('3 - Describing the query');
      dbms_sql.describe_columns(v_cursor, col_cnt, rec_tab);
      -- Use that description to define local datatypes into which we want to fetch our values
      -- Note: This only defines the types, it doesn't fetch any data and whilst we can also
      --       determine the size of the columns we'll just use some fixed sizes for this example
      dbms_output.put_line(chr(10)||'3a - SQL Projection:-');
      for j in 1..col_cnt
      loop
        v_finaltxt := 'Column Name: '||rpad(upper(rec_tab(j).col_name),30,' ');
        case rec_tab(j).col_type
          -- if the type of column is varchar2, bind that to our varchar2 variable
          when 1 then
            dbms_sql.define_column(v_cursor,j,v_v_val,20);
            v_finaltxt := v_finaltxt||' Datatype: Varchar2';
          -- if the type of the column is number, bind that to our number variable
          when 2 then
            dbms_sql.define_column(v_cursor,j,v_n_val);
            v_finaltxt := v_finaltxt||' Datatype: Number';
          -- if the type of the column is date, bind that to our date variable
          when 12 then
            dbms_sql.define_column(v_cursor,j,v_d_val);
            v_finaltxt := v_finaltxt||' Datatype: Date';
          -- ...Other types can be added as necessary...
        else
          -- All other types we'll assume are varchar2 compatible (implicitly converted)
          dbms_sql.DEFINE_COLUMN(v_cursor,j,v_v_val,2000);
          v_finaltxt := v_finaltxt||' Datatype: Varchar2 (implicit)';
        end case;
        dbms_output.put_line(v_finaltxt);
      end loop;
      -- 4. Bind variables
      dbms_output.put_line(chr(10)||'4 - Binding in values');
      null; -- we have no values to bind in for our test
      -- 5. Execute the query to make it identify the data on the database (Selection)
      -- Note: This doesn't fetch any data, it just identifies what data is required.
      dbms_output.put_line('5 - Executing the query');
      dummy := dbms_sql.execute(v_cursor);
      -- 6.,7.,8. Fetch the rows of data...
      dbms_output.put_line(chr(10)||'6,7 and 8 Fetching Data:-');
      loop
        -- 6. Fetch next row of data
        v_ret := dbms_sql.fetch_rows(v_cursor);
        -- If the fetch returned no row then exit the loop
        exit when v_ret = 0;
        -- 7. Extract the values from the row
        v_finaltxt := null;
        -- loop through each of the Projected columns
        for j in 1..col_cnt
        loop
          case rec_tab(j).col_type
            -- if it's a varchar2 column
            when 1 then
              -- read the value into our varchar2 variable
              dbms_sql.column_value(v_cursor,j,v_v_val);
              v_finaltxt := ltrim(v_finaltxt||','||rpad(v_v_val,20,' '),',');
            -- if it's a number column
            when 2 then
              -- read the value into our number variable
              dbms_sql.column_value(v_cursor,j,v_n_val);
              v_finaltxt := ltrim(v_finaltxt||','||to_char(v_n_val,'fm999999'),',');
            -- if it's a date column
            when 12 then
              -- read the value into our date variable
              dbms_sql.column_value(v_cursor,j,v_d_val);
              v_finaltxt := ltrim(v_finaltxt||','||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'),',');
          else
            -- read the value into our varchar2 variable (assumes it can be implicitly converted)
            dbms_sql.column_value(v_cursor,j,v_v_val);
            v_finaltxt := ltrim(v_finaltxt||',"'||rpad(v_v_val,20,' ')||'"',',');
          end case;
        end loop;
        dbms_output.put_line(v_finaltxt);
        -- 8. Loop to fetch next row
      end loop;
      -- 9. Close the cursor
      dbms_output.put_line(chr(10)||'9 - Closing the cursor');
      dbms_sql.close_cursor(v_cursor);
    END;
    SQL> exec process_cursor('select * from proj_test');
    1 - Opening Cursor
    2 - Parsing the query
    3 - Describing the query
    3a - SQL Projection:-
    Column Name: ID                             Datatype: Number
    Column Name: RN                             Datatype: Number
    Column Name: NM                             Datatype: Varchar2
    4 - Binding in values
    5 - Executing the query
    6,7 and 8 Fetching Data:-
    1     ,1     ,Fred
    1     ,2     ,Bloggs
    2     ,1     ,Scott
    2     ,2     ,Smith
    3     ,1     ,Jim
    3     ,2     ,Jones
    1     ,3     ,Freddy
    1     ,4     ,Fud
    9 - Closing the cursor
    PL/SQL procedure successfully completed.
    So, what's really the point in knowing when SQL Projection occurs in a query?
    Well, we get many questions asking "How do I convert rows to columns?" (otherwise known as a pivot) or questions like "How can I get the data back from a dynamic query with different columns?"
    Let's look at a regular pivot. We would normally do something like...
    SQL> select id
      2        ,max(decode(rn,1,nm)) as nm_1
      3        ,max(decode(rn,2,nm)) as nm_2
      4  from proj_test
      5  group by id
      6  /
            ID NM_1   NM_2
             1 Fred   Bloggs
             2 Scott  Smith
             3 Jim    Jones
    (or, in 11g, use the new PIVOT statement)
    but many of these questioners don't understand it when they say their issue is that, they have an unknown number of rows and don't know how many columns it will have, and they are told that you can't do that in a single SQL statement. e.g.
    SQL> insert into proj_test (id, rn, nm) values (1,3,'Freddy');
    1 row created.
    SQL> select id
      2        ,max(decode(rn,1,nm)) as nm_1
      3        ,max(decode(rn,2,nm)) as nm_2
      4  from proj_test
      5  group by id
      6  /
            ID NM_1   NM_2
             1 Fred   Bloggs
             2 Scott  Smith
             3 Jim    Jones
    ... it's not giving us this 3rd entry as a new column and we can only get that by writing the expected columns into the query, but then what if more columns are added after that etc.
    If we look back at the steps of a cursor we see again that the description and projection of what columns are returned by a query happens before any data is fetched back.
    Because of this, it's not possible to have the query return back a number of columns that are based on the data itself, as no data has been fetched at the point the projection is required.
    So, what is the answer to getting an unknown number of columns in the output?
    1) The most obvious answer is, don't use SQL to try and pivot your data. Pivoting of data is more of a reporting requirement and most reporting tools include the ability to pivot data either as part of the initial report generation or on-the-fly at the users request. The main point about using the reporting tools is that they query the data first and then the pivoting is simply a case of manipulating the display of those results, which can be dynamically determined by the reporting tool based on what data there is.
    2) The other answer is to write dynamic SQL. Because you're not going to know the number of columns, this isn't just a simple case of building up a SQL query as a string and passing it to the EXECUTE IMMEDIATE command within PL/SQL, because you won't have a suitable structure to read the results back into as those structures must have a known number of variables for each of the columns at design time, before the data is know. As such, inside PL/SQL code, you would have to use the DBMS_SQL package, just like in the code above that showed the workings of a cursor, as the columns there are referenced by position rather than name, and you have to deal with each column seperately. What you do with each column is up to you... store them in an array/collection, process them as you get them, or whatever. They key thing though with doing this is that, just like the reporting tools, you would need to process the data first to determine what your SQL projection is, before you execute the query to fetch the data in the format you want e.g.
    create or replace procedure dyn_pivot is
      v_sql varchar2(32767);
      -- cursor to find out the maximum number of projected columns required
      -- by looking at the data
      cursor cur_proj_test is
        select distinct rn
        from   proj_test
        order by rn;
    begin
      v_sql := 'select id';
      for i in cur_proj_test
      loop
        -- dynamically add to the projection for the query
        v_sql := v_sql||',max(decode(rn,'||i.rn||',nm)) as nm_'||i.rn;
      end loop;
      v_sql := v_sql||' from proj_test group by id order by id';
      dbms_output.put_line('Dynamic SQL Statement:-'||chr(10)||v_sql||chr(10)||chr(10));
      -- call our DBMS_SQL procedure to process the query with it's dynamic projection
      process_cursor(v_sql);
    end;
    SQL> exec dyn_pivot;
    Dynamic SQL Statement:-
    select id,max(decode(rn,1,nm)) as nm_1,max(decode(rn,2,nm)) as nm_2,max(decode(rn,3,nm)) as nm_3 from proj_test group by id order by id
    1 - Opening Cursor
    2 - Parsing the query
    3 - Describing the query
    3a - SQL Projection:-
    Column Name: ID                             Datatype: Number
    Column Name: NM_1                           Datatype: Varchar2
    Column Name: NM_2                           Datatype: Varchar2
    Column Name: NM_3                           Datatype: Varchar2
    4 - Binding in values
    5 - Executing the query
    6,7 and 8 Fetching Data:-
    1     ,Fred                ,Bloggs              ,Freddy
    2     ,Scott               ,Smith               ,
    3     ,Jim                 ,Jones               ,
    9 - Closing the cursor
    PL/SQL procedure successfully completed.
    ... and if more data is added ...
    SQL> insert into proj_test (id, rn, nm) values (1,4,'Fud');
    1 row created.
    SQL> exec dyn_pivot;
    Dynamic SQL Statement:-
    select id,max(decode(rn,1,nm)) as nm_1,max(decode(rn,2,nm)) as nm_2,max(decode(rn,3,nm)) as nm_3,max(decode(rn,4,nm)) as nm_4 from proj_test group by id order by id
    1 - Opening Cursor
    2 - Parsing the query
    3 - Describing the query
    3a - SQL Projection:-
    Column Name: ID                             Datatype: Number
    Column Name: NM_1                           Datatype: Varchar2
    Column Name: NM_2                           Datatype: Varchar2
    Column Name: NM_3                           Datatype: Varchar2
    Column Name: NM_4                           Datatype: Varchar2
    4 - Binding in values
    5 - Executing the query
    6,7 and 8 Fetching Data:-
    1     ,Fred                ,Bloggs              ,Freddy              ,Fud
    2     ,Scott               ,Smith               ,                    ,
    3     ,Jim                 ,Jones               ,                    ,
    9 - Closing the cursor
    PL/SQL procedure successfully completed.
    Of course there are other methods, using dynamically generated scripts etc. (see Re: 4. How do I convert rows to columns?), but the above simply demonstrates that:-
    a) having a dynamic projection requires two passes of the data; one to dynamically generate the query and another to actually query the data,
    b) it is not a good idea in most cases as it requires code to handle the results dynamically rather than being able to simply query directly into a known structure or variables, and
    c) a simple SQL statement cannot have a dynamic projection.
    Most importantly, dynamic queries prevent validation of your queries at the time your code is compiled, so the compiler can't check that the column names are correct or the tables names, or that the actual syntax of the generated query is correct. This only happens at run-time, and depending upon the complexity of your dynamic query, some problems may only be experienced under certain conditions. In effect you are writing queries that are harder to validate and could potentially have bugs in them that would are not apparent until they get to a run time environment. Dynamic queries can also introduce the possibility of SQL injection (a potential security risk), especially if a user is supplying a string value into the query from an interface.
    To summarise:-
    The projection of an SQL statement must be known by the SQL engine before any data is fetched, so don't expect SQL to magically create columns on-the-fly based on the data it's retrieving back; and, if you find yourself thinking of using dynamic SQL to get around it, just take a step back and see if what you are trying to achieve may be better done elsewhere, such as in a reporting tool or the user interface.
    Other articles in the PL/SQL 101 series:-
    PL/SQL 101 : Understanding Ref Cursors
    PL/SQL 101 : Exception Handling

    excellent article. However there is one thing which is slightly erroneous. You don't need a type to be declared in the database to fetch the data, but you do need to declare a type;
    here is one of my unit test scripts that does just that.
    DECLARE
    PN_CARDAPPL_ID NUMBER;
    v_Return Cci_Standard.ref_cursor;
    type getcardapplattrval_recordtype
    Is record
    (cardappl_id ci_cardapplattrvalue.cardappl_ID%TYPE,
    tag ci_cardapplattrvalue.tag%TYPE,
    value ci_cardapplattrvalue.value%TYPE
    getcardapplattrvalue_record getcardapplattrval_recordtype;
    BEGIN
    PN_CARDAPPL_ID := 1; --value must be supplied
    v_Return := CCI_GETCUSTCARD.GETCARDAPPLATTRVALUE(
    PN_CARDAPPL_ID => PN_CARDAPPL_ID
    loop
    fetch v_return
    into getcardapplattrvalue_record;
    dbms_output.put_line('Cardappl_id=>'||getcardapplattrvalue_record.cardappl_id);
    dbms_output.put_line('Tag =>'||getcardapplattrvalue_record.tag);
    dbms_output.put_line('Value =>'||getcardapplattrvalue_record.value);
    exit when v_Return%NOTFOUND;
    end loop;
    END;

  • PL/SQL Parameterized Exceptions?

    I develop on the Oracle EBS platform and so I have to develop using multiple general purpose programming languages.  Mainly PL/SQL and Java but we also use Ruby and Korn Shell for example.  One thing I have trouble with in PL/SQL is exception handling.  I would really like to be able to provide additional information in an Exception in PL/SQL but don't know how to do so.  One way would be to define an exception with parameters.  Thus providing some slots to stick information into when raising an exception and then using the information when the exception is caught.  I've used raise_application_error that provides slots for a number and text but that's not really my idea of a good solution to this issue.  I like the Ruby Exception object approach myself that allows you to define the slots yourself via sub-classing an Exception class.  I've used OO PL/SQL successfully in certain solutions and I know it works but there are some serious shortcomings that make OO PL/SQL a bit of a no-mans land in my opinion so I think an Exception class in PL/SQL is probably not the way to go at this point but I could be wrong.  So I thought how about defining exceptions with parameters much like a procedure or function.  Is this coming or are there ways to provide additional information in an exception that you have used successfully?
    Thank you

    I got an error when I compiled your procedure
    SQL> create or replace procedure myexception (v  number) is
      2    v1   emp.empno%type;
      3    begin
      4    select empno into v1 from emp where empno=v;
      5    exception when no_data_found then
      6    dbms_output.put_line('No data found');
      7    Do first thing----
      8    when too_many_rows then
      9    dbms_output.put_line('Too many rows');
    10    Do second thing----
    11    when others then
    12    --Do third thing
    13    end;
    14    .
    15   /
    Warning: Procedure created with compilation errors.
    SQL> sho err
    Errors for PROCEDURE MYEXCEPTION:
    LINE/COL ERROR
    13/3     PLS-00103: Encountered the symbol "END" when expecting one of the
             following:
             begin case declare exit for goto if loop mod null pragma
             raise return select update while with <an identifier>
             <a double-quoted delimited-identifier> <a bind variable> <<
             close current delete fetch lock insert open rollback
             savepoint set sql execute commit forall merge pipe
    SQL> create or replace procedure myexception (v  number) is
      2    v1   emp.empno%type;
      3  begin
      4    select empno into v1 from emp where empno=v;
      5  exception when no_data_found then
      6    dbms_output.put_line('No data found');
      7    Do first thing----
      8  when too_many_rows then
      9    dbms_output.put_line('Too many rows');
    10    Do second thing----
    11  when others then
    12    --Do third thing
    13 dbms_output.put_line(SQLERRM);
    14  end;
    15  /
    Procedure created.
    SQL>

  • Delete Statement Exception Handling

    Hi guys,
    I have a problem in my procedure. There are 3 parameters that I am passing into the procedure. I am matching these parameters to those in the table to delete one record at a time.
    For example if I would like to delete the record with the values ('900682',3,'29-JUL-2008') as parameters, it deletes the record from the table but then again when I execute it with the same parameters it should show me an error message but it again says 'Deleted the Transcript Request.....' Can you please help me with this?
    PROCEDURE p_delete_szptpsr_1 (p_shttran_id IN saturn.shttran.shttran_id%TYPE,
    p_shttran_seq_no IN saturn.shttran.shttran_seq_no%TYPE,
    p_shttran_request_date IN saturn.shttran.shttran_request_date%TYPE) IS
    BEGIN
    DELETE FROM saturn.shttran
    WHERE shttran.shttran_id = p_shttran_id
    and shttran.shttran_seq_no = p_shttran_seq_no
    and trunc(shttran_request_date) = trunc(p_shttran_request_date);
    DBMS_OUTPUT.PUT_LINE('Deleted the Transcript Request Seq No (' || p_shttran_seq_no || ') of the Student (' || p_shttran_id ||') for the requested date of (' || p_shttran_request_date ||')');
    COMMIT;
    EXCEPTION WHEN NO_DATA_FOUND THEN
    DBMS_OUTPUT.PUT_LINE('Error: The supplied Notre Dame Student ID = (' || p_shttran_id ||
    '), Transcript Request No = (' || p_shttran_seq_no || '), Request Date = (' || p_shttran_request_date || ') was not found.');
    END p_delete_szptpsr_1;
    Should I have a SELECT statement to use NO_DATA_FOUND ???

    A DELETE statement that deletes no rows (just like an UPDATE statement that updates no rows) is not an error to Oracle. Oracle won't throw any exception.
    If you want your code to throw an exception, you'll need to write that logic. You could throw a NO_DATA_FOUND exception yourself, i.e.
    IF( SQL%ROWCOUNT = 0 )
    THEN
      RAISE no_data_found;
    END IF;If you are just going to catch the exception, though, you could just embed whatever code you would use to handle the exception in your IF statement, i.e.
    IF( SQL%ROWCOUNT = 0 )
    THEN
      <<do something about the exception>>
    END IF;In your original code, your exception handler is just a DBMS_OUTPUT statement. That is incredibly dangerous in real production code. You are relying on the fact that the client has enabled output, that the client has allocated a large enough buffer, that the user is going to see the message, and that the procedure will never be called from any piece of code that would ever care if it succeeded or failed. There are vanishingly few situations where those are safe things to rely on.
    Justin

  • Issue with exception Handling in GG

    Hi,
    I have bi-directional DML replication setup. I have written a code in replication parameter for handling the exception , Exception handling is working fine my replicate process is not getting ABENDED but Issue is I am not geeting any rows in EXCEPTION table.I had gone through replicat report, there I had seen GG is trying to inser duplicate records in EXCEPTION TABLE and it is failing because of that .
    **Command for create Exception Table is-**
    create table ggs_admin.exceptions (
    rep_name      varchar2(8) ,
    table_name      varchar2(61) ,
    errno      number ,
    dberrmsg      varchar2(4000) ,
    optype               varchar2(20) ,
    errtype           varchar2(20) ,
    logrba               number ,
    logposition          number ,
    committimestamp      timestamp,
    CONSTRAINT pk_exceptions PRIMARY KEY (logrba, logposition, committimestamp)
    USING INDEX
    TABLESPACE INDX1
    TABLESPACE dbdat1
    My replication parameter is-
    GGSCI (db) 1> view params rep2
    -- Replicator parameter file to apply changes
    REPLICAT rep2
    ASSUMETARGETDEFS
    USERID ggs_admin, PASSWORD ggs_admin
    DISCARDFILE /u01/app/oracle/product/gg/dirdat/rep2_discard.dsc, PURGE
    -- Start of the macro
    MACRO #exception_handler
    BEGIN
    , TARGET ggs_admin.exceptions
    , COLMAP ( rep_name = "REP2"
    , table_name = @GETENV ("GGHEADER", "TABLENAME")
    , errno = @GETENV ("LASTERR", "DBERRNUM")
    , dberrmsg = @GETENV ("LASTERR", "DBERRMSG")
    , optype = @GETENV ("LASTERR", "OPTYPE")
    , errtype = @GETENV ("LASTERR", "ERRTYPE")
    , logrba = @GETENV ("GGHEADER", "LOGRBA")
    , logposition = @GETENV ("GGHEADER", "LOGPOSITION")
    , committimestamp = @GETENV ("GGHEADER", "COMMITTIMESTAMP"))
    , INSERTALLRECORDS
    , EXCEPTIONSONLY;
    END;
    -- End of the macro
    REPERROR (DEFAULT, EXCEPTION)
    --REPERROR (-1, EXCEPTION)
    --REPERROR (-1403, EXCEPTION)
    MAP scr.order_items, TARGET scr.order_items;
    MAP scr.order_items #exception_handler();
    GGSCI (db) 2>view params rep2
    MAP resolved (entry scr.order_items):
    MAP "scr"."order_items" TARGET ggs_admin.exceptions , COLMAP ( rep_name = "REP2" , table_name = @GETENV ("GGHEADER", "TABLENAME") , errno = @GETENV ("LASTERR", "DB
    ERRNUM") , dberrmsg = @GETENV ("LASTERR", "DBERRMSG") , optype = @GETENV ("LASTERR", "OPTYPE") , errtype = @GETENV ("LASTERR", "ERRTYPE") , logrba = @GETENV ("GGHEADER"
    , "LOGRBA") , logposition = @GETENV ("GGHEADER", "LOGPOSITION") , committimestamp = @GETENV ("GGHEADER", "COMMITTIMESTAMP")) , INSERTALLRECORDS , EXCEPTIONSONLY;;
    Using the following key columns for target table GGS_ADMIN.EXCEPTIONS: LOGRBA, LOGPOSITION, COMMITTIMESTAMP.
    2012-08-30 09:09:00 WARNING OGG-01154 SQL error 1403 mapping scr.order_items to scr.order_items OCI Error ORA-01403: no data found, SQL <DELETE FROM "scr"."order_items" WHERE "SUBSCRIBER_ID" = :b0>.
    2012-08-30 09:09:00 WARNING OGG-00869 OCI Error ORA-00001: unique constraint (GGS_ADMIN.PK_EXCEPTIONS) violated (status = 1). INSERT INTO "GGS_ADMIN"."EXCEPTIONS" ("R
    EP_NAME","TABLE_NAME","ERRNO","DBERRMSG","OPTYPE","ERRTYPE","LOGRBA","LOGPOSITION","COMMITTIMESTAMP") VALUES (:a0,:a1,:a2,:a3,:a4,:a5,:a6,:a7,:a8).
    2012-08-30 09:09:00 WARNING OGG-01004 Aborted grouped transaction on 'GGS_ADMIN.EXCEPTIONS', Database error 1 (OCI Error ORA-00001: unique constraint (GGS_ADMIN.PK_EX
    CEPTIONS) violated (status = 1). INSERT INTO "GGS_ADMIN"."EXCEPTIONS" ("REP_NAME","TABLE_NAME","ERRNO","DBERRMSG","OPTYPE","ERRTYPE","LOGRBA","LOGPOSITION","COMMITTIMES
    TAMP") VALUES (:a0,:a1,:a2,:a3,:a4,:a5,:a6,:a7,:a8)).
    2012-08-30 09:09:00 WARNING OGG-01003 Repositioning to rba 92383 in seqno 8.
    2012-08-30 09:09:00 WARNING OGG-01154 SQL error 1403 mapping scr.order_items to scr.order_items OCI Error ORA-01403: no data found, SQL <DELETE FROM "scr"."order_items" WHERE "SUBSCRIBER_ID" = :b0>.
    2012-08-30 09:09:00 WARNING OGG-01154 SQL error 1 mapping scr.order_items to GGS_ADMIN.EXCEPTIONS OCI Error ORA-00001: unique constraint (GGS_ADMIN.PK_EXCEPTIONS)
    violated (status = 1). INSERT INTO "GGS_ADMIN"."EXCEPTIONS" ("REP_NAME","TABLE_NAME","ERRNO","DBERRMSG","OPTYPE","ERRTYPE","LOGRBA","LOGPOSITION","COMMITTIMESTAMP") VAL
    UES (:a0,:a1,:a2,:a3,:a4,:a5,:a6,:a7,:a8).
    2012-08-30 09:09:00 WARNING OGG-01003 Repositioning to rba 92383 in seqno 8.
    When I am running command
    select * from exceptions;
    no row selected.
    Please help. Why duplicat rows trying to insert in Exception table.

    Remove (disable) the constraint on the exceptions table and see if inserts will take place. Do you really need that primary key?

  • Java.sql.SQLException: statement handle not executed

    hello,
    i am calling a stored procedure and its returns a REF CURSOR and i am getting intermittent exceptions below,
    org.springframework.jdbc.UncategorizedSQLException: Hibernate operation: could not execute query; uncategorized SQLException for SQL [{call
    xxxx_pkg(?,?)}]; SQL state [99999]; error code [17144]; statement handle not executed; nested exception is java.sql.SQLException: statement handle not executed
    and
    org.springframework.jdbc.UncategorizedSQLException: Hibernate operation: could not execute query; uncategorized SQLException for SQL [{call
    xxxx_pkg(?,?,?)}]; SQL state [99999]; error code [17009]; Closed Statement; nested exception is java.sql.SQLException: Closed Statement
    any clue what could be the issue,
    Regards
    GG

    its pretty simple have a java class calling hibernateTemplate's findByNamedQueryAndNamedParam method by passing the procedure name and binding parameters/values, and here is the stack
    org.springframework.jdbc.UncategorizedSQLException: Hibernate operation: could not execute query; uncategorized SQLException for SQL [{call
    xxx_pkg(?,?)}]; SQL state [99999]; error code [17144]; statement handle not executed; nested exception is java.sql.SQLException: statement handle not executed
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:83)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
    at org.springframework.orm.hibernate3.HibernateAccessor.convertJdbcAccessException(HibernateAccessor.java:424)
    at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:410)
    at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411)
    at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
    at org.springframework.orm.hibernate3.HibernateTemplate.findByNamedQueryAndNamedParam(HibernateTemplate.java:1006)
    Caused by: java.sql.SQLException: statement handle not executed
    at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
    at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:112)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:173)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:229)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:403)
    at oracle.jdbc.driver.T4CStatement.doDescribe(T4CStatement.java:701)
    at oracle.jdbc.driver.OracleStatement.getColumnIndex(OracleStatement.java:3355)
    at oracle.jdbc.driver.OracleResultSetImpl.findColumn(OracleResultSetImpl.java:2009)
    at oracle.jdbc.driver.OracleResultSet.getString(OracleResultSet.java:494)
    at org.hibernate.type.StringType.get(StringType.java:18)
    at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:163)
    at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:154)
    at org.hibernate.type.AbstractType.hydrate(AbstractType.java:81)
    at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2091)
    at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1380)
    at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1308)
    at org.hibernate.loader.Loader.getRow(Loader.java:1206)
    at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:580)
    at org.hibernate.loader.Loader.doQuery(Loader.java:701)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
    at org.hibernate.loader.Loader.doList(Loader.java:2217)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2108)
    at org.hibernate.loader.Loader.list(Loader.java:2103)
    at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:289)
    at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1696)
    at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:142)
    at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:152)
    at org.springframework.orm.hibernate3.HibernateTemplate$34.doInHibernate(HibernateTemplate.java:1015)
    at org.springframework.orm.hibernate3.HibernateTemplate$34.doInHibernate(HibernateTemplate.java:1)
    at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)

  • Exception Handling in ADF 10g

    Hi everybody,
    I want to develop an application and need exception handling.
    I have a helper application that contains this classes:
    MyADFPhaseListener extends ADFPhaseListener that return this: return new MyFacesPageLifecycle(),
    MyErrorHandler extends DCErrorHandlerImpl,
    MyFacesPageLifecycle extends FacesPageLifecycle that contain this methods:
    prepareModel(LifecycleContext ctx) that set my errorhandler with this: ctx.getBindingContext().setErrorHandler(new MyErrorHandler(true));
    and
    reportErrors(PageLifecycleContext ctx){
    DCBindingContainer bc = (DCBindingContainer)ctx.getBindingContainer();
    if (bc != null) {
    ArrayList<Exception> exceptions =new ArrayList<Exception>();
    exceptions = bc.getExceptionsList();
    if (exceptions != null) {
    /*handle exceptions*/
    My problem is here:
    when throw an exception in my app like this: throw new JboException("Don't do that.", "101", null);
    after create pagelifecycle and calling prepareModel(), reporterros() dose not call....!!!
    why?
    Edited by: 859070 on May 15, 2011 9:35 PM

    when click a button and call action of this button.
    please note:
    My helper application and main application are apart. I deploy helper application to jar file and use this jar file in main application.
    Maybe exceptions don`t send to reportErrors() method in MyPageLifeCycle class, because i create a test class like this:
    public class test {
    public static void main(String[] args) throws SQLException {
    ArrayList<Exception> exss = new ArrayList<Exception>();
    exss.add(new JboException("A fatal exception is occurred",
    "103", null));
    exss.add(new NullPointerException());
    exss.add(new SQLException());
    MyFacesPageLifecycle efpl =new MyFacesPageLifecycle();
    efpl.errorReporter(exss);
    Body of errorReporter(ArrayList<Exception>) method is like reportErrors(PageLifecycleContext) just parameter is different.
    public void errorReporter(ArrayList<Exception> excs) {
    if (excs != null) {
    for (Exception exception: excs) {
    if(exception instanceof JboException){
    System.out.println("JBOException is occurred here: "+exception.getMessage());
    else if(exception instanceof SQLException){
    System.out.println("SQLException is occurred here");
    else if(exception instanceof NullPointerException){
    System.out.println("NullPointerException is occurred here");
    else{
    and this handle exceptions list. My opinion is that exceptions between different applications(helper and main) are lost. is this correct?

  • Exception handling in App. package PeopleCode

    Hi,
    I am accessing a table that is on remote database using DBLink for an update/insert operation using SQLExec. I am trying to implement exception handling to account for the scenario where the remote database is offline so that transaction can continue. However when I use the try-catch block in the app. package PeopleCode somehow the processing does not seem to move forward from the error. The App. pacakage code is triggered by the handler of the service operation. The goal is to simply skip the SQLExec if the table is not available. I am not sure if there is any limitation to the fatal SQL errors which the try-catch can handle.
    As expected i get below error when running select on a view which has remote table in the SQL developer as remote database is down.
    ORA-12514: TNS:listener does not currently know of service requested in connect descriptor
    Has anyone enconutered similar issue with exception handling and best way to move forward in this scenario.
    Any response is much appreciated.
    Thanks,
    Gireesh

    I did this with PL/SQL once. Basically, you want to know if the remote database is available before you execute SQL against it. Here is my function. You can then SQLExec something like select 'x' from dual where my_package.link_available('the_link_name') = 1. If you get a result, then the db link is active. If you don't, it is not active.
    FUNCTION LINK_AVAILABLE(pv_name VARCHAR2)
      RETURN NUMBER AS
            lv_result PLS_INTEGER;
            lv_name   VARCHAR2(128);
        BEGIN
            lv_name := UPPER(pv_name);
            -- parameter check to avoid SQL injection with dynamic SQL below
            -- if the following selects no rows, it will fall through to exception
            -- and return 0;
            SELECT 1
              INTO lv_result
              FROM ALL_DB_LINKS
             WHERE DB_LINK = lv_name;
            -- if we made it this far, then the parameter was a valid db link name
            -- execute SQL to test
            EXECUTE IMMEDIATE 'SELECT 1 FROM PS_INSTALLATION@' || lv_name INTO lv_result;
            RETURN lv_result;
        EXCEPTION
            WHEN OTHERS THEN
                RETURN 0;
      END LINK_AVAILABLE;

  • Exception handling in report

    Hello all,
    i want oto implement exception handling in report.
    scenario:
    i have a parameter form par.fmb
    i provide parameter on form then call the report.
    if there is some error generate while query of report then how to handle it, so that user get the message.
    below query is used in report:
    SELECT SPC_ITEM_CODE,GENERATE_ITEM_NAME(SPC_ITEM_CODE),MOD_DATE,OBU,REQ_NO,REQ_QTY,OQC_QTY,SPC_ITEM_QTY,process
    , INSP_LOT_SIZE,REMARKS,INSP_STATUS
    FROM OQC_DATA
    WHERE (REQ_NO=:REQ_NO OR :REQ_NO IS NULL) AND trunc(MOD_DATE) BETWEEN :FROM_DATE AND :TO_DATE
    AND SPC_LOCN_CODE=:LOCN_CODE
    ORDER BY REQ_NO,SPC_ITEM_CODE
    here: GENERATE_ITEM_NAME(SPC_ITEM_CODE) is database function.
    as spc_item_code is column in OQC_DATA table, it any how there is null value in spc_item_code then error will raise, i and want to handle this error sothat ,
    i found the reason.
    Thanks
    yash
    Edited by: yash_08031983 on Jan 27, 2012 9:11 PM

    yash_08031983 wrote:
    Hello all,
    i want oto implement exception handling in report.
    scenario:
    i have a parameter form par.fmb
    i provide parameter on form then call the report.
    if there is some error generate while query of report then how to handle it, so that user get the message.
    below query is used in report:
    SELECT SPC_ITEM_CODE,GENERATE_ITEM_NAME(SPC_ITEM_CODE),MOD_DATE,OBU,REQ_NO,REQ_QTY,OQC_QTY,SPC_ITEM_QTY,process
    , INSP_LOT_SIZE,REMARKS,INSP_STATUS
    FROM OQC_DATA
    WHERE (REQ_NO=:REQ_NO OR :REQ_NO IS NULL) AND trunc(MOD_DATE) BETWEEN :FROM_DATE AND :TO_DATE
    AND SPC_LOCN_CODE=:LOCN_CODE
    ORDER BY REQ_NO,SPC_ITEM_CODE
    here: GENERATE_ITEM_NAME(SPC_ITEM_CODE) is database function.
    as spc_item_code is column in OQC_DATA table, it any how there is null value in spc_item_code then error will raise, i and want to handle this error sothat ,
    i found the reason.You can handle the error in two way.
    First from the function, you can use exception in it and through 0(zero) if it didn't get any value.
    2nd use nvl function in the sql like nvl(GENERATE_ITEM_NAME(SPC_ITEM_CODE),0) if number data type or NVL(GENERATE_ITEM_NAME(SPC_ITEM_CODE),'n/a') if char data type output.
    You can also use decode.
    Hope this will help you.

  • Exception handling in jinitiator

    hallo,
    we are currently using jinitiator 1.3.1.9 and i have a little question concerning the exception handling in it. i don't think, that the handling differes to older version, so maybe one can help me out though he uses an "older" version.
    now the problem. we use java functionality either in webmode (jinitiator) and in client-server-mode (wrapper pl/sql unit) and want to pass the java exception trace to the forms, so that we can handle errors in user interaction. we found a way to da that by developing a printstream, which collects trace information in a string. this method works well in client-server-mode but not in webmode. in the first case all the normal trace information is written with the printstream-method println(String). in the webmode case, a different method is used, println(char[]). the strange thing about it is, that the character array contains address information for an object (maybe the string). i my opinion the behaviour is because of the jinitiator. does anyone know about the exception handling and collecting the trace information in jinitiator?? thanks very much in advance.
    regards
    steffen silberbach

    hi again,
    thanks for answering, but I think you got me wrong or I didn't make myself clearly. I don't want to pass a PL/SQL error to the bean to have it printed out on the console. I want it the other wa around. my problem was to get the stack trace of a java exception and make it accessible to the form to print it out as a message for instance. unfortunately this way is quite impossible to do, because jinitiator has a different exception handling to the sun VM. the jinitiator implements the printStackTrace(*) methods as native calls and obviously the underlying code handles the addresses of the passed trace objects and prints them out the a special console somehow. so if one overwrites the printStack() methods in his own Exception, he gets a problem because of the different exception trace handling in jinitiator.

  • Exception Handling in the OBI EE 10.1.3.4

    Hi All,
    Is it possible to implement the exception handling in the OBI EE 10.1.3.4
    For Ex: Instead of displaying the below error, is it possible to display it in the meaningful way
    [nQSError: 10058] A general error has occurred. [nQSError: 27002] Near : Syntax error [nQSError: 26012] . (HY000)
    SQL Issued: SELECT SALES_FACT.SALES_AMOUNT, TIMESTAMPDIFF(SQL_TSI_DAY, TIMESTAMP ‘1900-01-01 12:00:00’, TIMESTAMP ‘1900-01-01 12:00:00’), TIME_DIM.BUSINESS_DATE FROM SALES
    Thanks in Advance
    Siva

    Hi Deepak,
    Thank you for responding to the query that i have raised.
    As you mentioned that ORA: errors will help in diagnosing the issue.
    Do you mean that it will help in diagnosing the issue at the BMM larey & Physical layer join conditions.
    Thanks in Advance
    Siva

  • Exception handling in stored process, loop IF..ELSE

    Hello Guys,
    we want to put in exception handling in the loop but get the following error:
    Error(43,3): PLS-00103: Encountered the symbol "EXCEPTION" when expecting one of the following: begin case declare end exit for goto if loop mod null pragma raise return select update while with <an identifier> <a double-quoted delimited-identifier> <a bind variable> << close current delete fetch lock insert open rollback savepoint set sql execute commit forall merge pipe
    create or replace
    PROCEDURE xxxx
    FOR MESSSY IN
    select I.*
    FROM x I
    LOOP
    IF upper(CODE)='N' THEN
    INSERT INTO T_MESS(MP)
    select I.MP_ID
    FROM T_ME
    ELSIF upper(MESSSY.k2)='L' THEN
    DELETE T_MESS WHERE T_MESS.MP = MESSSY.MP;
    END IF;
    EXCEPTION
    WHEN DUP_VAL_ON_INDEX THEN
    A program attempted to insert duplicate values in a column that is constrained by a unique index.
    DBMS_OUTPUT.PUT_LINE ('A program attempted to insert duplicate values in a column that is constrained by a unique index.')
    --No Rollback
    END;
    COMMIT;
    END LOOP;
    END xxxx;
    does someone know why?

    BluShadow wrote:
    Well, your code is missing all sorts of bits and we don't have your data or your exact logic to know what it's supposed to be achieving.
    That is right, you dont have my data and that is why I was suprised by your comment.
    Since the input table might contain a few thousand rows and each of those might need to
    be considered N , D, or C and each case has a different handling I can not imagine how this
    can be all done with a merge statement.
    MERGE
    T_METRICPOINT_META with T_METRICSSYSTEM_LOAD where T_METRICSSYSTEM_LOAD .LOAD_DATE=to_char(sysdate)
    WHEN MATCHED THEN --we know those are the metric points that have to be loaded today, but we still need to do a IF..ELSE to handle them
    WHEN NOT MATCHED THEN -- not considered in todays load
    ----original code-----
    create or replace
    PROCEDURE myprocedure AS
    BEGIN
    --Extracting the records from T_METRICSSYSTEM_LOAD which have todays load date. Corresponding to these MP_System, we extract the MP_IDs from the T_METRICPOINT_META table.
    --Comapring these MP_IDs with the MP_IDs from the source(T_METRICPOINT_IMPORT) and extracting only those Metric points which need to be loaded today.
    FOR METRICSSYSTEM IN
    select I.*
    FROM T_METRICPOINT_IMPORT I
    where I.LOADDATE = TO_CHAR(SYSDATE) AND I.MP_ID IN
    (select a.MP_ID
    from T_METRICPOINT_META a INNER JOIN T_METRICSSYSTEM_LOAD b on a.MP_SYSTEM = b.MP_SYSTEM where b.LOAD_DATE=to_char(sysdate))
    LOOP
    --If mutation code in the source/import data is "N", the record is inserted as it is in the "T_METRICPOINTS" table.
    IF upper(METRICSSYSTEM.MUTATIONCODE)='N' THEN --new
    INSERT INTO T_METRICPOINTS(MP_ID, ......)
    SELECT DISTINCT I.MP_ID,.....
    FROM T_METRICPOINT_IMPORT I WHERE I.MP_ID = METRICSSYSTEM.MP_ID
    ELSIF upper(METRICSSYSTEM.MUTATIONCODE)='D' THEN --delete
    DELETE T_METRICPOINTS WHERE T_METRICPOINTS.MP_ID = METRICSSYSTEM.MP_ID AND T_METRICPOINTS.KEY = METRICSSYSTEM.KEY;
    ELSIF upper(METRICSSYSTEM.MUTATIONCODE)='C' THEN --correction
    UPDATE T_HISTORYMETRICPOINTS H
    SET CHANGE_DATE = to_char(sysdate)
    WHERE H.MP_ID=METRICSSYSTEM.MP_ID AND H.KEY = METRICSSYSTEM.KEY;
    INSERT INTO T_HISTORYMETRICPOINTS(MP_ID, KEY, .....)
    --The distinct here is used, to handle 2 identical records in the input table with correction value "C". This would insert into 1 record in the T_HISTORYMETRICPOINTS table without
    --violating the primary key constraint.
    select DISTINCT I.MP_ID,I.KEY, ....
    FROM T_METRICPOINT_IMPORT I WHERE I.MP_ID = METRICSSYSTEM.MP_ID
    --END IF;
    END IF;
    COMMIT;
    END LOOP;
    END myprocedure;

  • Exception handler activity doesn't execute

    I have an exception handler in my bounded task flow but it not always executes when an error is raised by some of the BTF activities.
    In my application I'm having a problem with connections closed.
    I don't know if the database, the firewall or who is closing connections but sometimes I get an error in the logs "oracle.jbo.JboException: JBO-29000: Se ha obtenido una excepción inesperada: java.sql.SQLRecoverableException, mensaje=Conexión cerrada" translation "oracle.jbo.JboException: JBO-29000: Un unexpected exception has been raised: java.sql.SQLRecoverableException, message=Closed connection".
    That is bothering me specially because my task flow continues execution despite of the error. ADF opens the connection and then continues execution. This is fatal because previous updating in the entity objects is lost and the consequence is very bad.
    Well, I have tried to insert an exception handler in my task flow in order to capture this errors and then stop execution of the task flow.
    Currently, I'm more upset because of task flow continues execution after the connection closed error that for the error itself.
    The problem is that sometimes the connection closed appears in the log window but the exception handler is not executed. Sometimes yes, some others no.
    In order to test I'm forcing the error manually killing the sessions in the server.
    Any help for any of both problems ? (1- BTF continuing execution after this error raising and 2-Why the exception handler doesn't always execute when a java error stack appears in the log window).
    Thank you.

    this might be caused by a bug I found too causing eventhandlers not to work, the work round in your case would be:
    blar blar blar
    </variables>
    <!-- start work round --><scope><!-- end work round -->
    <faultHandlers>
    blar blar blar
    blar blar blar
    </sequence>
    <!-- start work round --></scope><!-- end work round -->
    </process>
    i.e. what I'm saying is that top level handler don't work since they are ignored by the engine because they are not in a scope. Try it and see....

Maybe you are looking for

  • Insufficient Bandwidth STILL a Problem

    I've followed the instructions listed here: http://docs.info.apple.com/article.html?artnum=301641 Still coming up short. Can anbody provide some other trouble-shooting tips. Also, I don't know if this is important, but I am presently in Rome, Italy a

  • Process Flow of Creating and sending Dunning Form

    Hi Experts, Can you please help me in this What is the process flow of creating, sending Dunning form and when do we get Confirmation from vendor and when the condition type should be triggered in messages of PO. I will appriciate your help Regards,

  • 8-bit B/W image question

    Hi, does anyone know how the color table in "Draw 8-bit pixmap.vi" exactly works?  I get an 8-bit image through RS-232 which is B/W and I want to project the value of the pixels as follows: 0:black , 255:white , 1-254:nuances of gray. Could you send

  • KeyStore Algorithm & Cipher Algorithm

    Hi,      Generated the KeyStore using the keytool using Default KeyStrore Type & KeyStore = User, Password=password      With keystore am able to retrieve the both Private & Public Keys by making use of KeyStore.getDefaultType())      When i tried 2

  • IPhone chooses Bluetooth  instead of handset

    My iPhone is paired to the handsfree device in my car ('07 Altima Hybrid), but to no other device. Sometimes when I am nowhere near my car, I try to place a call, and the iPhone automatically chooses Bluetooth instead of the iPhone handset. The call